在看了这些多线程的知识之后,突发奇想到怎么让多线程有序执行呢?
第一种:用Thread.join()方法来确定该线程执行完毕
第二种:用线程池的队列来执行任务
第三种:用公共锁Object,配合wait/notifyAll方法,睡眠自己,唤醒另一个线程~
join方法是阻塞的,会一定等到取消或者超时为止,这样就可以按顺序来。
@Slf4j
public class JoinExample {
public static void main(String[] args) throws InterruptedException{
log.info("{} is start", Thread.currentThread().getName());
Thread t0 = new Thread(() -> {
try{
log.info( "{} is Start,sleep 6 second", Thread.currentThread().getName());
Thread.sleep(6000);
log.info("{} is Completed", Thread.currentThread().getName());
}catch (InterruptedException e){
log.error("exception", e);
}
});
t0.start();
t0.join();
Thread t1 = new Thread(() -> {
try{
log.info( "{} is Start,sleep 2 second", Thread.currentThread().getName());
Thread.sleep(2000);
log.info( "{} is Completed", Thread.currentThread().getName());
}catch (InterruptedException e){
log.error("exception", e);
}
});
t1.start();
t1.join();
log.info("{} is Completed", Thread.currentThread().getName() );
}
}
再来一个,
@Slf4j
public class JoinExample1 {
public static void main(String[] args) {
final Thread t1 = new Thread(() -> {
log.info("{} is first", Thread.currentThread().getName());
},"线程1");
final Thread t2 = new Thread(() -> {
try {
t1.join();
log.info("{} is second", Thread.currentThread().getName());
}catch (InterruptedException e){
log.info("exception", e);
}
},"线程2");
final Thread t3 = new Thread(() -> {
try {
t2.join();
log.info("{} is third", Thread.currentThread().getName());
}catch (InterruptedException e){
log.info("exception", e);
}
},"线程3");
t2.start();
t3.start();
t1.start();
//顺序sart是没有关系的
}
}
@Slf4j
public class JoinExample2 {
public static void main(String[] args) {
final Thread t1 = new Thread(() -> {
log.info("{}, the first 运行了!", Thread.currentThread().getName());
},"线程1");
final Thread t2 = new Thread(() -> {
log.info("{}, the second 运行了!", Thread.currentThread().getName());
}, "线程2");
final Thread t3 = new Thread(() -> {
log.info("{}, the third 运行了!", Thread.currentThread().getName());
}, "线程3");
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.submit(t1);
exec.submit(t2);
exec.submit(t3);
exec.shutdown();
}
}
由于线程池中只有一个,所以默认就它一个能运行的线程~~