Java线程中的notifyAll唤醒操作(推荐)

2025-05-29 0 54

注意:

java中的notifyAll和notify都是唤醒线程的操作,notify只会唤醒等待池中的某一个线程,但是不确定是哪一个线程notifyAll是针对指定对象里面的所有线程执行唤醒操作,指定对象一旦唤醒成功。则会立即加入线程的资源争夺中去。

例如:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47
package TestThread.ThreadSynchronized;

public class TestWaitAll {

public static void main(String[] args) {

Test1 test1 = new Test1();

Thread t = new Thread(test1, "线程1");

Thread t1 = new Thread(test1, "线程2");

Thread t2 = new Thread(test1, "线程3");

Test2 test2 = new Test2(test1, "唤醒线程");

t.start();

t1.start();

t2.start();

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

test2.start();

}

}

class Test1 implements Runnable {

public void run() {

synchronized (this) {

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName() + "当前没有被执行到!");

}

}

}

class Test2 extends Thread {

private Test1 test1;

String name;

public Test2(Test1 test1, String name) {

super(name);

this.name = name;

this.test1 = test1;

}

public void run() {

synchronized (test1) {

test1.notifyAll();// 针对当前对象执行唤醒所有线程的操作

System.out.println(Thread.currentThread().getName() + ":唤醒线程执行成功!");

}

}

}

执行结果为:

Java线程中的notifyAll唤醒操作(推荐)

以上所述是小编给大家介绍的Java线程中的notifyAll唤醒操作,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

原文链接:http://www.cnblogs.com/chaiyesong/archive/2017/03/24/6610110.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java线程中的notifyAll唤醒操作(推荐) https://www.kuaiidc.com/117985.html

相关文章

发表评论
暂无评论