public class test2 { public static void main(String[] args) throws InterruptedException { Data1 data = new Data1(); new Thread(()->{ for ( int i = 0; i< 10 ;i++){ data.prinA(); } },"A").start(); new Thread(()->{ for ( int i = 0; i< 10 ;i++){ data.prinB(); } },"B").start(); new Thread(()->{ for ( int i = 0; i< 10 ;i++){ data.prinC(); } },"C").start(); } } class Data1{ Lock lock =new ReentrantLock(); private Condition condition1 = lock.newCondition(); private Condition condition2 = lock.newCondition(); private Condition condition3 = lock.newCondition(); private int number = 1; public void prinA(){ lock.lock(); try { //if可能会出现虚假唤醒 while (number != 1){ condition1.await(); } System.out.println(Thread.currentThread().getName()+"=>AAAA"); number = 2; // 唤醒 B线程 condition2.signal(); }catch (InterruptedException e) { e.printStackTrace(); }finally { // 关锁 lock.unlock(); } } public void prinB(){ lock.lock(); try { while (number != 2){ condition1.await(); } System.out.println(Thread.currentThread().getName()+"=>BBBBBB"); number = 3; // 唤醒 B线程 condition2.signal(); }catch (InterruptedException e) { e.printStackTrace(); }finally { // 关锁 lock.unlock(); } } public void prinC(){ lock.lock(); try { while (number != 3){ condition1.await(); } System.out.println(Thread.currentThread().getName()+"=>CCCC"); number = 1; // 唤醒 B线程 condition2.signal(); }catch (InterruptedException e) { e.printStackTrace(); }finally { // 关锁 lock.unlock(); } } }
生产者消费者问题
最新推荐文章于 2023-12-02 21:00:58 发布