gpt4 book ai didi

java - 简单的 Ping Pong Java 线程

转载 作者:行者123 更新时间:2023-11-30 07:51:58 25 4
gpt4 key购买 nike

我正在尝试使 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

最佳答案

Table 类中的同步(顺便说一下,不需要扩展 Thread)仅保证 Ping 和 Pong 线程以交替方式获取其字符串。它不保证它们以交替的方式打印字符串。

例如,可能会发生以下顺序:

Ping gets its first ping, call it ping 1.
Ping prints ping 1.
Pong gets its first pong, call it pong 1.
Ping gets ping 2.
Ping prints ping 2.
Pong prints pong 1.
Pong gets pong 2.
Pong prints pong 2.
Ping gets ping 3.
Pong gets pong 3.
Pong prints pong 3.
Ping prints ping 3.

请注意,每个线程都在获取其字符串和打印它之间交替,并且两个线程以交替的顺序获取其字符串。然而,在一个线程获取字符串和打印该字符串之间,另一个线程可能会也可能不会获得时间。这会导致交替序列被打乱以进行打印,在我们的示例中,输出为:

ping
ping
pong
pong
pong
ping

如果你想解决这个问题,你需要在同一个同步块(synchronized block)中包含获取字符串和打印它,并且你可能需要该 block 在 System.out 和 Table 上同步。

关于java - 简单的 Ping Pong Java 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33238225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com