gpt4 book ai didi

java - 了解多线程等待和通知

转载 作者:行者123 更新时间:2023-12-02 11:56:28 24 4
gpt4 key购买 nike

我正在学习多线程,我试图了解如何使用 Object 类的等待和通知方法。我已经浏览过这个链接https://www.journaldev.com/1037/java-thread-wait-notify-and-notifyall-example并编写了以下程序

服务员

public class Waiter implements Runnable {
private Message m;
public Waiter(Message m) {
this.m = m;
}
public void run() {
String name = Thread.currentThread().getName();
System.out.println(t1 + " thread waiting for message");
synchronized (m) {
try {
m.wait();
System.out.println(t1 + " " + m.getText());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(t1 + " thread waiting for message");
}
}

通知者

public class Notifier implements Runnable {
private Message m;
public Notifier(Message m) {
this.m = m;
}
public void run() {
synchronized (m) {
try {
Thread.sleep(2000);
m.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

测试

public class WaitNotifyTest {
public static void main(String[] str) {
Message m = new Message("hello");
new Thread(new Waiter(m), "t1").start();
new Thread(new Waiter(m), "t2").start();
new Thread(new Notifier(m)).start();
}
}

当我执行程序时,它有时会正确终止,有时会无限期等待,有时一个线程终止而另一个线程无限期等待。谁能告诉我这里出了什么问题吗?

我还想了解一些等待和通知方法实时应用的例子。

最佳答案

当您进行等待时,最佳实践是在带有条件的 while 循环中执行。可能存在线程发出通知,然后其他线程进入等待状态的情况。因此线程将始终处于等待状态

修改后的代码:

public class Waiter implements Runnable {
private Message m;

public Waiter(Message m) {
this.m = m;
}

public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + " thread waiting for message");
synchronized (m) {
try {
while (m.getText() == null) {
m.wait();
}
System.out.println(name + " " + m.getText());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name + " thread waiting for message");
}
}

public class Notifier implements Runnable {
private Message m;

public Notifier(Message m) {
this.m = m;
}

public void run() {
synchronized (m) {

m.setText("hello");
m.notifyAll();

}
}
}

public class WaitNotifyTest {
public static void main(String[] str) {
Message m = new Message();
new Thread(new Waiter(m), "t1").start();
new Thread(new Waiter(m), "t2").start();
new Thread(new Notifier(m)).start();
}
}

关于java - 了解多线程等待和通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47569003/

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