java notify 会唤醒_java – 在单个线程上发出notify唤醒所有等待的线程

有三个线程在第4个线程上等待,后者发出通知,所有等待的线程都被唤醒.

这是源代码:

class Reader extends Thread {

Calculator calc;

public Reader(Calculator calc) {

this.calc = calc;

}

public void run() {

synchronized(calc) {

try {

System.out.println(Thread.currentThread().getName() + " waiting for calc");

calc.wait();

} catch (InterruptedException e) { e.printStackTrace(); }

System.out.println(Thread.currentThread().getName() + " Total is: " + calc.total);

}

}

}

class Calculator extends Thread {

public int total = 0;

public void run() {

synchronized(this) {

for (int i = 0; i < 50; i++) {

total += i;

}

notify();

System.out.println("I notified a thread");

}

}

}

public class Notify {

public static void main(String[] args) {

Calculator calc = new Calculator();

Reader r1 = new Reader(calc);

Reader r2 = new Reader(calc);

Reader r3 = new Reader(calc);

r1.start();

r2.start();

r3.start();

calc.start();

}

}

这是我得到的输出:

Thread-2 waiting for calc

Thread-4 waiting for calc

Thread-3 waiting for calc

I notified a thread

Thread-2 Total is: 1225

Thread-3 Total is: 1225

Thread-4 Total is: 1225

不应该只唤醒一个等待线程并执行System.out.println(Thread.currentThread().getName()“Total is:”calc.total);指导?

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值