有兩種實現(xiàn)方式,第一種是采用join,第二種是采用Executors框架
- join方式通過讀代碼可以知道,在join內(nèi)部采用的是wait方法,也就是主線程等待,所以可以實現(xiàn)線程的順序執(zhí)行。
- 采用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í)行");
}
}
}