最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Java线程中的notifyAll唤醒操作(推荐)
时间:2017-07-26 编辑:简简单单 来源:一聚教程网
java中的notifyAll和notify都是唤醒线程的操作,notify只会唤醒等待池中的某一个线程,但是不确定是哪一个线程,notifyAll是针对指定对象里面的所有线程执行唤醒操作,指定对象一旦唤醒成功。则会立即加入线程的资源争夺中去。
例如:
代码如下 | 复制代码 |
packageTestThread.ThreadSynchronized; publicclassTestWaitAll { publicstaticvoidmain(String[] args) { Test1 test1 =newTest1(); Thread t =newThread(test1,"线程1"); Thread t1 =newThread(test1,"线程2"); Thread t2 =newThread(test1,"线程3"); Test2 test2 =newTest2(test1,"唤醒线程"); t.start(); t1.start(); t2.start(); try{ Thread.sleep(2000); }catch(InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } test2.start(); } } classTest1implementsRunnable { publicvoidrun() { synchronized(this) { try{ this.wait(); }catch(InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() +"当前没有被执行到!"); } } } classTest2extendsThread { privateTest1 test1; String name; publicTest2(Test1 test1, String name) { super(name); this.name = name; this.test1 = test1; } publicvoidrun() { synchronized(test1) { test1.notifyAll();// 针对当前对象执行唤醒所有线程的操作 System.out.println(Thread.currentThread().getName() +":唤醒线程执行成功!"); } } } |
执行结果为:
-
上一个: java连接数据库(代码分享)
-
下一个: java 虚拟机中对象访问详解
相关文章
- SpringBoot测试配置属性与web启动环境解析 10-24
- vue中将el-switch值true、false改为number类型的1和0解析 10-24
- Vue中的路由配置项meta使用解读 10-24
- SpringBoot自定义bean绑定解析 10-24
- SpringBoot常用计量与bean属性校验和进制数据转换规则解析 10-24
- 工厂方法在Spring框架中的运用介绍 10-24