如何控制多线程执行顺序?
方法一:Join()使用。 原理:让主线程等待子线程运行结束后才能继续运行。 方法二:ExecutorService ()的使用。 原理:利用并发包里的Excutors的newSingleThreadExecutor产生一个单线程的线程池,而这个线程池的底层原理就是一个先进先出(FIFO)的队列。 代码中executor.submit依次添加了123线程,按照FIFO的特性,执行顺序也就是123的执行结果,从而保证了执行顺序。
示例代码: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
public class Test { public static void main(String[] args) throws InterruptedException { // thread1.start(); // thread1.join(); // // thread2.start(); // thread2.join(); // // thread3.start();
// executorService.submit(thread1); // executorService.submit(thread2); // executorService.submit(thread3); // // executorService.shutdown(); }
static Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread1");
}
});
static Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread2");
}
});
static Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread3");
}
});
static ExecutorService executorService = Executors.newSingleThreadExecutor();
}