天天看點

并發面試題 三條線程同時啟動,順序列印abc十遍ReentrantLock Condition實作

package cn.wukala.wk;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Test {
    private  static CountDownLatch countDownLatch =new CountDownLatch(1);
    private static ReentrantLock reentrantLock = new ReentrantLock();
    private static String now = "a";

    static Condition ca = reentrantLock.newCondition();
    static Condition cb = reentrantLock.newCondition();
    static Condition cc = reentrantLock.newCondition();

    public static void main(String[] args) {
        Thread b= new Thread(new Worker("b"));
        Thread a= new Thread(new Worker("a"));
        Thread c= new Thread(new Worker("c"));
           a.start();
           b.start();
           c.start();
        countDownLatch.countDown();

    }
     static class Worker implements Runnable{
        String s;

        Worker(String s){
            this.s=s;
        }

        @Override
        public void run() {
            try {
                countDownLatch.await(); // 等待其它線程
                System.out.println(s+"啟動");

                reentrantLock.lock();
                if(!s.equals(now)){//不是你的請放手
                    if(s.equals("a")){
                        ca.await();

                    }else if(s.equals("b")){
                        cb.await();

                    }else {
                        cc.await();
                    }
                }
                for(int i=0;i<10;i++){
                    System.out.println(s);

                    if(s.equals("a")){
                        now="b";
                        cb.signal();
                        ca.await();

                    }else if(s.equals("b")){
                        now="c";
                        cc.signal();
                        cb.await();

                    }else {
                        now="a";
                        ca.signal();
                        cc.await();
                    }


                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                reentrantLock.unlock();
            }
        }
    }


}