两线程交替打印单双数
创建A,B两个线程交替打印1-100,A线程打印单数,B线程打印双数
package com.advance.code.learn.day0226; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * 两个线程交替打印 1-100的数 */ public class TurnedPrintThread { public static void main(String[] args) { PrinterHandler printerHandler = new PrinterHandler(); new Thread(() -> { for (int i = 1; i <= 100; i += 2) { printerHandler.printer(i, true); } }, "AAAAAA").start(); new Thread(() -> { for (int i = 2; i <= 100; i += 2) { printerHandler.printer(i, false); } }, "BBBBBB").start(); } } class PrinterHandler{ //用于标记当前线程 true是A线程 flag是B线程 private boolean flag = true; private ReentrantLock lock = new ReentrantLock(); Condition condition1 = lock.newCondition(); Condition condition2 = lock.newCondition(); public void printer(int num, boolean flagThread){ lock.lock(); try { while (flagThread != flag){ if(flagThread){ condition1.await(); }else{ condition2.await(); } } System.out.println(Thread.currentThread().getName() + "打印:\t"+num); if(flagThread){ flag = false; condition2.signal(); }else{ flag = true; condition1.signal(); } }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } }