如何控制多線程執行順序


如果我們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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM