all在java语言什么意思,notify()和notifyAll()在我的java代码中不起作用

所以我一直在使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值