美文网首页
三个线程顺序打印

三个线程顺序打印

作者: FlySheep_ly | 来源:发表于2017-03-28 20:47 被阅读102次

忽然想到之前的一个面试题:三个线程顺序打印 ABC,该怎么实现?于是又自己动手写了一遍。

public class ThreadABC {

    private static boolean printA = true;
    private static boolean printB = false;
    private static boolean printC = false;

    public static void main(String[] args) {
        final ThreadABC threadABC = new ThreadABC();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (threadABC) {
                    while (true) {
                        while (!printA) {
                            try {
                                threadABC.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        System.out.println("A");
                        printA = false;
                        printB = true;
                        printC = false;
                        threadABC.notifyAll();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (threadABC) {
                    while (true) {
                        while (!printB) {
                            try {
                                threadABC.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        System.out.println("B");
                        printA = false;
                        printB = false;
                        printC = true;
                        threadABC.notifyAll();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (threadABC) {
                    while (true) {
                        while (!printC) {
                            try {
                                threadABC.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        System.out.println("C");
                        printA = true;
                        printB = false;
                        printC = false;
                        threadABC.notifyAll();
                    }
                }
            }
        }).start();
    }
}

相关文章

网友评论

      本文标题:三个线程顺序打印

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