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 | /** * @author 五月的仓颉http://www.cnblogs.com/xrq730/p/7067904.html */ @Test public void testCondition() throws Exception { Lock lock = new ReentrantLock(); Condition condition = lock.newCondition(); // 线程0的作用是signal Runnable runnable0 = new ConditionThread(lock, condition); Thread thread0 = new Thread(runnable0); thread0.setName("线程0"); // 线程1的作用是await Runnable runnable1 = new ConditionThread(lock, condition); Thread thread1 = new Thread(runnable1); thread1.setName("线程1"); // 线程2的作用是lock Runnable runnable2 = new ConditionThread(lock, condition); Thread thread2 = new Thread(runnable2); thread2.setName("线程2"); thread1.start(); Thread.sleep(1000); thread0.start(); Thread.sleep(1000); thread2.start(); thread1.join(); } |
1 2 3 4 5 6 | 1 线程1阻塞 2 线程0休息5秒 3 线程2想要获取锁 4 线程0唤醒等待线程 5 线程2获取锁成功 6 线程1被唤醒 |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |