如何保證線程的執行順序(面試題)

一:案例數據 (模擬多線程)

public class ThreadTest {

    static Thread t1 = new Thread(new Runnable() {
       @Override
       public void run() {
           System.err.println("t1 執行");
       }
   });

    static Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.err.println("t2 執行");
        }
    });


    static Thread t3 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.err.println("t3 執行");
        }
    });
    
}


二:解決方案

1)設置線程的執行優先級(此方案不行

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

        //1:設置優先級(不能保證線程的執行順序,只能加大執行的概率) 不行
        t1.setPriority(Thread.MIN_PRIORITY);
        t1.start();
        t2.start();
        t3.start();
    }

2)join方法 (主線程阻塞,激活,阻塞,激活去依次執行t1,t2,t3) 可以 (比較基礎,join方法是同步方法)

public static void main(String[] args) throws InterruptedException{
        t1.start();
        t1.join();
        t2.start();
        t2.join();
        t3.start();
        t3.join();  
    }

3)單例線程池 (阻塞隊列,先進先出,只有一個核心主線程在執行) 可以,推薦

public static void main(String[] args) throws InterruptedException{
        //3:單例線程池  (阻塞隊列,先進先出)
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(t1);
        executorService.submit(t2);
        executorService.submit(t3);
        executorService.shutdown();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章