阅读背景:

【面试】--三个线程轮流打印ABC_qfzhangwei的专栏

来源:互联网 

1 lock实现

 

public class ABCLock {

    private static Lock lock = new ReentrantLock();
    private static Condition conditionA = lock.newCondition();
    private static Condition conditionB = lock.newCondition();
    private static Condition conditionC = lock.newCondition();


    private static int count = 1;

    private static Thread threadA = new Thread(new Runnable() {
        @Override
        public void run() {

            while (true) {
                try {
                    lock.lock();

                    while (count % 3 == 1) {

                        System.out.print("A");
                        Thread.sleep(500);
                        count++;

                    }

                } catch (Exception e) {

                } finally {
                    lock.unlock();
                }

            }
        }
    });

    private static Thread threadB = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {

                try {
                    lock.lock();

                    while (count % 3 == 2) {

                        System.out.print("B");
                        Thread.sleep(500);
                        count++;

                    }

                } catch (Exception e) {

                } finally {
                    lock.unlock();
                }
            }
        }

    });
    private static Thread threadC = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {

                try {
                    lock.lock();
                    while (count % 3 == 0) {

                        System.out.print("C");
                        Thread.sleep(500);
                        count++;

                    }

                } catch (Exception e) {

                } finally {
                    lock.unlock();
                }

            }
        }
    });

    public static void main(String[] args) throws InterruptedException {
        threadA.start();
        threadB.start();
        threadC.start();
        Thread.currentThread().join();
    }
}public class ABCLock {

    priv



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: