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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | /** * @author 五月的仓颉http://www.cnblogs.com/xrq730/p/7067904.html */ public class ConditionThread implements Runnable { private Lock lock; private Condition condition; public ConditionThread(Lock lock, Condition condition) { this.lock = lock; this.condition = condition; } @Override public void run() { if ("线程0".equals(JdkUtil.getThreadName())) { thread0Process(); } else if ("线程1".equals(JdkUtil.getThreadName())) { thread1Process(); } else if ("线程2".equals(JdkUtil.getThreadName())) { thread2Process(); } } private void thread0Process() { try { lock.lock(); System.out.println("线程0休息5秒"); JdkUtil.sleep(5000); condition.signal(); System.out.println("线程0唤醒等待线程"); } finally { lock.unlock(); } } private void thread1Process() { try { lock.lock(); System.out.println("线程1阻塞"); condition.await(); System.out.println("线程1被唤醒"); } catch (InterruptedException e) { } finally { lock.unlock(); } } private void thread2Process() { try { System.out.println("线程2想要获取锁"); lock.lock(); System.out.println("线程2获取锁成功"); } finally { lock.unlock(); } } } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |