所以我一直在使用Java中的简单等待/通知示例,由于某种原因我无法使其正常运行.如果有人能够看到可能是什么问题,将非常感谢!
class producer implements Runnable {
StringBuffer sb;
producer() {
sb=new StringBuffer("");
}
public void run () {
synchronized(sb) {
for(int i = 0; i < 10; i++) {
try {
sb.append(i+" ");
System.out.println("Appending ... ");
} catch (Exception e) {}
}
sb.notify();
}
}
}
class consumer implements Runnable {
producer p;
consumer(producer pp) {
this.p = pp;
}
public void run() {
System.out.println("Rreached");
synchronized(p.sb) {
try {
p.sb.wait();
} catch (Exception e) {}
System.out.println(p.sb);
}
}
}
class Thread_Comunication {
public static void main (String [] args) {
producer p = new producer();
consumer c = new consumer(p);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
输出:
Appending ...
Rreached // randome Position
Appending ...
Appending ...
Appending ...
Appending ...
Appending ...
Appending ...
Appending ...
Appending ...
Appending ...
所以由于某种原因线程t1没有唤醒t2或者我完全错过了其他东西?
解决方法:
除非另一个线程在等待,否则Notify不会执行任何操作.您的代码完全取决于通知(需要条件变量的位置),并依赖于在生产者之前运行的消费者才能使其生效.
根据你的输出,生产者首先运行;它将在消费者有机会运行之前完整执行. (对于消费者运行它需要获取生成器所持有的sb上的锁.)生产者调用notify但没有线程在等待,所以它没有效果.然后消费者等待并且没有通知,所以它无限期地挂起.
如果消费者先运行,那么代码将正常终止.
避免编写依赖于一个线程在另一个线程之前运行的代码,因为您无法控制先执行的操作.当你等待时,你需要在一个测试条件的循环中进行.其中一个原因是,如果在线程开始等待之前设置了条件,则线程可以知道不等待.
更改代码以使用条件:
import java.io.*;
class producer implements Runnable {
StringBuffer sb;
boolean done = false;
producer() {
sb=new StringBuffer("");
}
public void run () {
synchronized(sb) {
for(int i=0;i<10;i++) {
try {
sb.append(i+" ");
System.out.println("Appending ... ");
} catch (Exception e) {}
}
sb.notify();
done = true;
}
}
}
class consumer implements Runnable {
producer p;
consumer(producer pp) {
this.p=pp;
}
public void run() {
System.out.println("Rreached");
synchronized(p.sb) {
try {
while (!p.done) {
p.sb.wait();
}
} catch (Exception e) {}
System.out.println(p.sb);
}
}
}
public class Communication {
public static void main (String [] args) throws Exception {
producer p= new producer();
consumer c= new consumer(p);
Thread t1= new Thread(p);
Thread t2= new Thread(c);
t2.start();
t1.start();
}
}
标签:java,multithreading,wait,synchronized,notify
来源: https://codeday.me/bug/20190623/1267891.html