该程序的期望输出是:
乒乓乒乓乒乓
然而它在那个和之间交替
乒乓球等
问题是,我创建了 Ping 线程并首先运行它。所以我不确定为什么 Pong 偶尔会排在第一位。
所以这是我的代码(易于编译)。它基本上有效。我只是不明白为什么它有时会先打印“Pong”。有人可以解释一下为什么会这样吗?
// Printer class - will be the object that both threads lock / synchronize onto
class Printer
{
int numberOfMessages;
int messageCount;
// Constructor allowing user to choose how many messages are displayed
Printer(int numberOfMessages)
{
this.numberOfMessages = numberOfMessages;
this.messageCount = 0;
}
// If more messages are to be printed, print and increment messageCount
void printMsg(String msg)
{
if (messageCount < numberOfMessages)
{
System.out.println("[" + msg + "]");
++messageCount;
}
else
{
System.exit(0);
}
}
}
// PingPong thread
class PingPongThread extends Thread
{
Printer printer;
String message;
public PingPongThread(Printer printer, String message)
{
this.printer = printer;
this.message = message;
this.start();
}
@Override
public void run()
{
while(true)
{
synchronized (printer)
{
// Print message whether it is Ping or Pong
printer.printMsg(message);
// Notify
printer.notify();
// Wait
try
{
printer.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
// Two threads communicate with eachother to alteratively print out "Ping" and "Pong"
public class PingPong
{
public static void main(String args[])
{
Printer printer = new Printer(6);
PingPongThread pingThread = new PingPongThread(printer, "Ping");
PingPongThread pongThread = new PingPongThread(printer, "Pong");
}
}