package com.lyon.juc; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; //生产线 有序执行的工序 //A调用B,B调用C,C调用A 依次循环 public class C { public static void main(String[] args) { Data2 data2 = new Data2(); new Thread(()->{ for (int i = 0; i < 10; i++) { data2.printA(); } },"A").start(); new Thread(()->{ for (int i = 0; i < 10; i++) { data2.printB(); } },"B").start(); new Thread(()->{ for (int i = 0; i < 10; i++) { data2.printC(); } },"C").start(); } } class Data2{ private Lock lock = new ReentrantLock(); private Condition condition1 = lock.newCondition(); private Condition condition2 = lock.newCondition(); private Condition condition3 = lock.newCondition(); private int number = 1; //1A 2B 3C public void printA(){ lock.lock(); try { //业务代码,判断-> 执行-> 通知 while (number!=1){ //等待 condition1.await(); } System.out.println(Thread.currentThread().getName()+"=>A"); number = 2; condition2.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printB(){ lock.lock(); try { //业务代码,判断-> 执行-> 通知 while (number!=2){ //等待 condition2.await(); } System.out.println(Thread.currentThread().getName()+"=>B"); number = 3; condition3.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printC(){ lock.lock(); try { //业务代码,判断-> 执行-> 通知 //业务代码,判断-> 执行-> 通知 while (number!=3){ //等待 condition3.await(); } System.out.println(Thread.currentThread().getName()+"=>C"); number = 1; condition1.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }
多线程之juc版线程有序循环执行
最新推荐文章于 2023-04-17 18:01:07 发布