JAVA中如何按順序執(zhí)行多線程

有兩種實現(xiàn)方式,第一種是采用join,第二種是采用Executors框架

  1. join方式通過讀代碼可以知道,在join內(nèi)部采用的是wait方法,也就是主線程等待,所以可以實現(xiàn)線程的順序執(zhí)行。
  2. 采用Executors的newSingleThreadExecutor創(chuàng)建一個只有一個線程的線程池,在向該線程池中添加任務(wù)時,除了當(dāng)前正在執(zhí)行的任務(wù)其余的會被加入到LinkedBlockingQueue隊列中,隊列是先進先出的FIFO,所以可以實現(xiàn)按順序執(zhí)行。
    代碼如下:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadOrderDemo {

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

        System.out.println("main --- before");
//        threadOrderJoin();
        threadOrderExcutor();
        System.out.println("main --- after");
    }

    private static void threadOrderExcutor() {
        //隊列的最大值為Integer.MAX_VALUE,走默認(rèn)拒絕策略,直接拋出異常
        //拒絕策略有4中,1. 直接拋出異常 2. 立即嘗試執(zhí)行超出隊列的任務(wù) 3. 丟棄最新的任務(wù)  4. 丟棄最舊的數(shù)據(jù)
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for(int i = 0; i < 100; i++) {
            //excute submit 區(qū)別:一個有返回值一個沒有,如果不需要返回值直接用excute
            executorService.execute(new ThreadDemo("線程" + i));
        }
        executorService.shutdown();
    }

    private static void threadOrderJoin() throws InterruptedException {
        for(int i = 1; i < 100; i++) {
            Thread t1 = new Thread(new ThreadDemo(),"線程" + i);
            t1.start();
            t1.join();
        }
    }

    private static class ThreadDemo implements Runnable {
        private String name = "";
        public ThreadDemo(){};

        public ThreadDemo(String name){
            this.name = name;
        };
        @Override
        public void run() {
            System.out.println(name + ":[" + Thread.currentThread().getName() + "]:正在執(zhí)行");
        }
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容