JS 与 trick 代码的运用及解析全攻略
701
2022-09-03
JUC(2)使用condition实现精准通知唤醒
package com.orderPC;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * 执行A,然后B,然后C,然后A */public class ProductC { public static void main(String[] args) { Data3 data3 = new Data3(); new Thread(()->{ for (int i = 0; i <5 ; i++) { data3.printA(); } },"A").start(); new Thread(()->{ for (int i = 0; i < 5; i++) { data3.printB(); } },"B").start(); new Thread(()->{ for (int i = 0; i < 5; i++) { data3.printC(); } },"C").start(); }}//资源类class Data3{ private Lock lock = new ReentrantLock(); Condition condition1 = lock.newCondition(); Condition condition2 = lock.newCondition(); Condition condition3 = lock.newCondition(); private int num = 1; public void printA(){ lock.lock(); try { while(num != 1){ //等待 condition1.await(); } System.out.println(Thread.currentThread().getName()+"-->AAA"); num=2; //唤醒,唤醒指定的 condition2.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printB(){ lock.lock(); try { while(num !=2 ){ condition2.await(); } System.out.println(Thread.currentThread().getName()+"-->BBB"); num =3; //唤醒指定线程 condition3.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printC(){ lock.lock(); try { while(num != 3){ //等待 condition3.await(); } System.out.println(Thread.currentThread().getName()+"-->CCC"); num = 1; condition1.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~