阿里面试真题:ABC三个线程如何保证顺序执行?

其实这一个题有很多解,面试官想听的可能是CountDownLatch这一种,因为面试官也只会这一种。。

参考了网络不过总体思路没错。

public class ThreadOderRun {

    public static void main(String[] args) {
        ThreadOderRun threadOderRun = new ThreadOderRun();
        CountDownLatch l1 = new CountDownLatch(0);
        CountDownLatch l2 = new CountDownLatch(1);
        CountDownLatch l3 = new CountDownLatch(1);
        Thread work1 = new Thread(threadOderRun.new Work(l1, l2, "1"));
        Thread work2 = new Thread(threadOderRun.new Work(l2, l3, "2"));
        Thread work3 = new Thread(threadOderRun.new Work(l3, l3, "3"));
        work1.start();
        work2.start();
        work3.start();
    }


    class Work implements Runnable {
        CountDownLatch c1;
        CountDownLatch c2;
        String msg;

        public Work(CountDownLatch c1, CountDownLatch c2, String msg) {
            this.c1 = c1;
            this.msg = msg;
            this.c2=c2;
        }

        public void run() {
            try {
                c1.await();
                System.out.println(msg);
                c2.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

如果能多几种方式就更好了

public class ThreadOrderRun2 {

    private AtomicInteger val = new AtomicInteger(1);

    public static void main(String[] args) {
        ThreadOrderRun2 threadOrderRun2 = new ThreadOrderRun2();
        Thread work1 = new Thread(threadOrderRun2.new Work("1", 1));
        Thread work2 = new Thread(threadOrderRun2.new Work("2", 2));
        Thread work3 = new Thread(threadOrderRun2.new Work("3", 3));
        work1.start();
        work2.start();
        work3.start();
    }


    class Work implements Runnable {
        private String msg;
        private int order;

        public Work(String msg, Integer order) {
            this.msg = msg;
            this.order = order;
        }

        public void run() {
            while (true) {
                try {
                    Thread.sleep(100);
                    if (val.get() == order) {
                        System.out.println(msg);
                        val.incrementAndGet();
                        break;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

参见这个博客吧:https://blog.csdn.net/Evankaka/article/details/80800081

发布了224 篇原创文章 · 获赞 100 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/chenpeng19910926/article/details/103791137