lock+condition实现两个线程循环打印奇偶数:0~100
程序员文章站
2022-04-19 08:23:28
...
/** * @author lanwei 2018-05-19 */ public class ConditonPrintAB { public static void main(String[] a) { PrintAB printAB = new PrintAB(); new Thread(() -> printAB.print1()).start(); new Thread(() -> printAB.print2()).start(); } public static class PrintAB { private Lock lock = new ReentrantLock(); private Condition c1 = lock.newCondition(); private Condition c2 = lock.newCondition(); private volatile int state = 0; /** * 打印奇数 */ public void print1() { print(1, c1, c2); } /** * 打印偶数 */ public void print2() { print(0, c2, c1); } public void print(int flag, Condition cuerrentConditon, Condition nextConditin) { for (; ; ) { try { lock.lock(); // 状态判断 while (state % 2 == flag) { cuerrentConditon.await(); } if (state > 100) { return; } System.out.println(Thread.currentThread().getName() + ": " + state++); nextConditin.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } } }
上一篇: Java中的锁