美文网首页
三个线程按顺序重复打印ABC

三个线程按顺序重复打印ABC

作者: sendos | 来源:发表于2019-03-11 22:44 被阅读0次

以前面试被虐的一道多线程题目

public class PrintABC {
    Lock lock = new ReentrantLock();  //可重写锁
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    public class printA implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 15; i++) {
                lock.lock();
                System.out.print("A");
                conditionB.signal();
                try {
                    conditionA.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public class printB implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 15; i++) {
                lock.lock();
                System.out.print("B");
                conditionC.signal();
                try {
                    conditionB.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public class printC implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 15; i++) {
                lock.lock();
                System.out.print("C");
                conditionA.signal();
                try {
                    conditionC.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}
public static void main(String[] args) throws Exception {
        PrintABC printABC = new PrintABC();
        new Thread(printABC.new printA()).start();
        new Thread(printABC.new printB()).start();
        new Thread(printABC.new printC()).start();
        return;
    }

相关文章

网友评论

      本文标题:三个线程按顺序重复打印ABC

      本文链接:https://www.haomeiwen.com/subject/letwpqtx.html