线程按序交替
/* * Copyright (c) XXX Corp. * All Rights Reserved. */ import java.util.concurrent.ExecutionException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Main. * * @author Feng Yongkang, 2020/10/26 * @version XXX v1.0 */ public class Main { public static void main(String[] args) throws InterruptedException, ExecutionException { AlternateDemo alternateDemo = new AlternateDemo(); new Thread(() -> { for (int i = 0; i < 5; i++) { alternateDemo.loop1(); } }, "线程A").start(); new Thread(() -> { for (int i = 0; i < 5; i++) { alternateDemo.loop2(); } }, "线程B").start(); new Thread(() -> { for (int i = 0; i < 5; i++) { alternateDemo.loop3(); } }, "线程C").start(); } } class AlternateDemo {
//交替的信号 private int number = 1; private Lock lock = new ReentrantLock();
//多线程下控制方法跟随信号执行 private Condition condition1 = lock.newCondition(); private Condition condition2 = lock.newCondition(); private Condition condition3 = lock.newCondition(); public void loop1() { lock.lock(); try { if (number != 1) { condition1.await(); } System.out.println(Thread.currentThread().getName()); number = 2; condition2.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void loop2() { lock.lock(); try { if (number != 2) { condition2.await(); } System.out.println(Thread.currentThread().getName()); number = 3; condition3.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void loop3() { lock.lock(); try { if (number != 3) { condition3.await(); } System.out.println(Thread.currentThread().getName()); number = 1; condition1.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }