JAVA JUC 线程按顺序执行
class demo{ private ReentrantLock lock =new ReentrantLock(); private Condition cb = lock.newCondition(); private Condition cc = lock.newCondition(); private Condition ca = lock.newCondition(); private int num = 1; public void loopA(int epoch){ lock.lock(); try { if(num!=1){ ca.await(); } for(int i=0;i<5;i++){ System.out.println(Thread.currentThread().getName()+" "+i+"\t"+epoch); } num=2; cb.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void loopB(int epoch){ lock.lock(); try { if(num!=2){ cb.await(); } for(int i=0;i<5;i++){ System.out.println(Thread.currentThread().getName()+" "+i+"\t"+epoch); } num=3; cc.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void loopC(int epoch){ lock.lock(); try { if(num!=3){ cc.await(); } for(int i=0;i<5;i++){ System.out.println(Thread.currentThread().getName()+" "+i+"\t"+epoch); } num=1; ca.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } public class alterDemo { public static void main(String[] args) { demo d = new demo(); new Thread(new Runnable() { @Override public void run() { for(int i=0;i<20;i++) { d.loopA(i); } } },"A").start(); new Thread(new Runnable() { @Override public void run() { for(int i=0;i<20;i++) { d.loopB(i); } } },"B").start(); new Thread(new Runnable() { @Override public void run() { for(int i=0;i<20;i++) { d.loopC(i); } } },"C").start(); } }