如何控制多线程执行顺序

如果我们new了好几个线程,然后开始执行,肯定不是按照顺序执行的,因为多线程.start()方法开始执行之后,并不意味着立即执行,而是到就绪状态,等待cpu的调度,cpu如何调度,那我们就没法知道了,但是如何让线程按照指定的顺序来执行呢?我们可以利用线程的join方法。join()方法的主要作用是让正在执行的线程停止,让join的这个线程立刻执行并结束。

看例子:

public static void main(String[] arg) throws InterruptedException {

        Thread thread1 = new Thread(() -> System.out.println("111111"));
        Thread thread2 = new Thread(() -> System.out.println("222222"));
        Thread thread3 = new Thread(() -> System.out.println("333333"));
        Thread thread4 = new Thread(() -> System.out.println("444444"));

        thread1.start();
        thread1.join();
        thread2.start();
        thread2.join();
        thread3.start();
        thread3.join();
        thread4.start();
        thread4.join();
    }

结果肯定是按照顺序来的

111111
222222
333333
444444

不信的话,可以把join方法去掉试试。

jdk5以后出来一个类,可以简化这样的操作,new一个线程池,把线程放到线程池里执行,同样可以按照顺序执行。

        Thread thread1 = new Thread(() -> System.out.println("111111"));
        Thread thread2 = new Thread(() -> System.out.println("222222"));
        Thread thread3 = new Thread(() -> System.out.println("333333"));
        Thread thread4 = new Thread(() -> System.out.println("444444"));

        ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
        threadExecutor.submit(thread1);
        threadExecutor.submit(thread2);
        threadExecutor.submit(thread3);
        threadExecutor.submit(thread4);

        threadExecutor.shutdown();
原文地址:https://www.cnblogs.com/coder-lzh/p/9404103.html