我正在尝试制作 2 个线程,一个 Ping 和一个 Pong。这个想法是 Ping 应该总是首先执行。我正在使用同步方法。我不确定我的代码有什么问题。在我看来它应该可以工作。我已经阅读了很多文档。因此,如果您有任何您认为会有所帮助的内容,我将很乐意阅读。我确定这很简单。任何帮助表示赞赏
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