juc控制執行緒輪詢輸出
阿新 • • 發佈:2018-12-17
大家推薦個靠譜的公眾號程式設計師探索之路,大家一起加油,這個公眾號已經接入圖靈
package com.zzh; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class TestLoop { /** * 目的 a,b,c三個執行緒輪詢輸出A,B,C * 思路: * 用num標記是A,B,C * 方法裡判斷如果是自己就列印並且把標記更新成下一個 * 如果不是自己就等待 */ public static void main(String[] args) { final Loop loop = new Loop(); new Thread(new Runnable() { @Override public void run() { //列印10輪 for (int i = 1;i <= 10;i++){ loop.loopA(i); } } },"A").start(); new Thread(new Runnable() { @Override public void run() { for (int i = 1;i <= 10;i++){ loop.loopB(i); } } },"B").start(); new Thread(new Runnable() { @Override public void run() { for (int i = 1;i <= 10;i++){ loop.loopC(i); } } },"C").start(); } } class Loop{ private int num = 1; private Lock lock = new ReentrantLock(); private Condition condition1 = lock.newCondition(); private Condition condition2 = lock.newCondition(); private Condition condition3 = lock.newCondition(); public void loopA(int totalLoop){ lock.lock(); try { //如果輪不到自己列印就 if (num != 1){ condition1.await(); } //輸出 System.out.println(Thread.currentThread().getName()+"---輪次"+totalLoop); //喚醒b num = 2; condition2.signal(); }catch (Exception e){ }finally { lock.unlock(); } } public void loopB(int totalLoop){ lock.lock(); try { if (num != 2){ condition2.await(); } System.out.println(Thread.currentThread().getName()+"---輪次"+totalLoop); //喚醒c num = 3; condition3.signal(); }catch (Exception e){ }finally { lock.unlock(); } } public void loopC(int totalLoop){ lock.lock(); try { if (num != 3){ condition3.await(); } System.out.println(Thread.currentThread().getName()+"---輪次"+totalLoop); //喚醒A num = 1; condition1.signal(); }catch (Exception e){ }finally { lock.unlock(); } } }