1、多线程循环打印123
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class PrintThread { private Lock lock = new ReentrantLock(); private volatile int flag = 1; // 控制执行哪个线程 private Condition condition1 = lock.newCondition(); private Condition condition2 = lock.newCondition(); private Condition condition3 = lock.newCondition(); public static void main(String[] args) { PrintThread printThread = new PrintThread(); for (int i = 0; i < 10; i++) { new Thread(() -> printThread.printA(), "A").start(); new Thread(() -> printThread.printB(), "B").start(); new Thread(() -> printThread.printC(), "C").start(); } } public void printA() { lock.lock(); try { while (flag != 1) { condition1.await(); } System.out.println(Thread.currentThread().getName() + " : 1"); flag = 2; condition1.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printB() { lock.lock(); try { while (flag != 2) { condition2.await(); } System.out.println(Thread.currentThread().getName() + " : 2"); flag = 3; condition2.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printC() { lock.lock(); try { while (flag != 3) { condition3.await(); } System.out.println(Thread.currentThread().getName() + " : 3"); flag = 1; condition3.signalAll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }
。。。
标签:Thread,lock,打印,private,flag,123,new,多线程,public From: https://www.cnblogs.com/guoyu1/p/17936812