我正在嘗試使2個線程一個Ping和一個Pong。這個想法是Ping應該始終執行。我正在使用同步方法。我不確定這裏的代碼有什麼問題。它看起來像它應該工作。我已經閱讀了很多文檔。所以如果你有任何你認爲會有幫助的東西,我會很樂意閱讀它。我相信這很簡單。任何幫助表示讚賞簡單的Ping Pong Java線程
class Ping extends Thread {
private Table table;
private String text1 = "";
public Ping(Table t)
{
table = t;
}
public void run() {
for (int i = 0; i < 10; i++) {
text1= table.getPing();
System.out.println(text1);
}
}
}
class Pong extends Thread {
private Table table;
private String text1 = "";
public Pong(Table t)
{
table = t;
}
public void run() {
for (int i = 0; i < 10; i++) {
text1= table.getPong();
System.out.println(text1); }
}
}
class Table extends Thread {
private Table table;
private boolean pinged = false;
public synchronized String getPong() {
while (pinged == false) {
try {
//System.out.println("WAIT PONG");
wait();
}
catch (InterruptedException e)
{ }
}
pinged = false;
notifyAll();
String text = "pong";
return text;
}
public synchronized String getPing() {
while (pinged == true) {
try {
wait();
//System.out.println("WAIT PING");
} catch (InterruptedException e) { }
}
pinged = true;
notifyAll();
String text = "ping";
return text;
}
}
public class PingPong {
//private static final int WAIT_TIME = 200;
public static void main(String args[]) {
Table t = new Table();
Pong pong = new Pong(t);
Ping ping = new Ping(t);
System.out.println("main: starting threads...");
pong.start();
ping.start();
System.out.println("main: threads started, sleep a while " +
"and wait for termination of Ping and Pong");
System.out.println("both threads terminated");
}
}
每個結果是不同的,但奇怪的是我重複。
ping
pong
ping
ping
pong
pong
pong
ping
ping
ping
pong
pong
pong
ping
pong
ping
ping
pong
ping
pong
看來你未來的影響[同步和的System.out.println(http://stackoverflow.com/questions/9459657/synchronization-and-system-out-println) – alex2410