控制线程的执行顺序的两种方法
方法一:
利用Thread.join()的方法实现,其原理是,让其父线程等待子线程执行完再执行
package com.itheima.a_demo.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadDemo1 {
//线程1
static Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread111111111111111111111111111");
}
});
//线程2
static Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread22222222222222222222222222");
}
});
/**
* 如何控制这个执行顺序?
* 1) 通过线程的join方法来实现
*/
public static void main(String[] args) throws InterruptedException {
thread1.start();
thread1.join();// 让主线程阻塞,然后让thread1 执行完之后,才执行主线程
thread2.start();
thread2.join();//让主线程阻塞,然后让thread2 执行完之后,才执行主线程
}
}
部分源码:
进入了join()方法,然后再进入join(0)方法
public final void join() throws InterruptedException {
join(0);
}
可以看到当millis = 0 的时候,执行wati(0)方法让主线程阻塞。
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
方法二:
使用static ExecutorService es = Executors.newSingleThreadExecutor()的submit方法执行线程任务
package com.itheima.a_demo.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadDemo2 {
//线程1
static Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread111111111111111111111111111");
}
});
//线程2
static Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread22222222222222222222222222");
}
});
//线程3
static Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread33333333333333333333333333");
}
});
/**
* 如何控制这个执行顺序?
* 1) 通过线程的join方法来实现
* 2) 通过ExecutorService来实现
*
*/
//实例化一个 ExecutorService
static ExecutorService es = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException {
es.submit(thread1);
es.submit(thread2);
es.submit(thread3);
es.shutdown();
}
}
进入Executors.newSingleThreadExecutor();的源码
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
内部实现的是一个数量为1的线程池,这样就可以控制线程的执行顺序了。