このプログラムの望ましい出力は次のとおりです。
ピンポン ピンポン ピンポン
それでも、それと
ポンピンなど
問題は、Ping スレッドを作成して最初に実行することです。そのため、ポンが時折最初に来る理由がわかりません。
これが私のコードです(すぐにコンパイルできます)。それは本質的に機能します。「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");
}
}