1. 程式人生 > 實用技巧 >執行緒按序交替

執行緒按序交替

/*
 * 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(); } } }