通过join方法保证多线程的顺序性特性
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");
}
});
public static void main(String[] args) throws InterruptedException {
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
thread3.join();
}
join
让主线程等待子线程结束以后才能继续运行,执行流程如下:
执行流程.jpg
通过线程池保证多线程的顺序性特性
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();
public static void main(String[] args) throws InterruptedException {
executorService.execute(thread1);
executorService.execute(thread2);
executorService.execute(thread3);
executorService.shutdown();
}
源码
创建只有一个线程的线程池,适用于需要保证顺序地执行各个任务;并且在任意时间点,不会有多个线程是活动的应用场景。
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
网友评论