有两种实现方式,第一种是采用join,第二种是采用Executors框架
- join方式通过读代码可以知道,在join内部采用的是wait方法,也就是主线程等待,所以可以实现线程的顺序执行。
- 采用Executors的newSingleThreadExecutor创建一个只有一个线程的线程池,在向该线程池中添加任务时,除了当前正在执行的任务其余的会被加入到LinkedBlockingQueue队列中,队列是先进先出的FIFO,所以可以实现按顺序执行。
代码如下:
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,走默认拒绝策略,直接抛出异常
//拒绝策略有4中,1. 直接抛出异常 2. 立即尝试执行超出队列的任务 3. 丢弃最新的任务 4. 丢弃最旧的数据
ExecutorService executorService = Executors.newSingleThreadExecutor();
for(int i = 0; i < 100; i++) {
//excute submit 区别:一个有返回值一个没有,如果不需要返回值直接用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() + "]:正在执行");
}
}
}