目录
并发编程的重点:多线程之间的同步,依赖synchornized,wait & notify,AQS和基于Lock的各种实现。
9种方法实现多线程的顺序执行,定义thread1、thread2、thread3,要求执行顺序为:thread1 > thread2 > thread3
1 使用线程的join方法
线程依次join前序执行的线程;
Thread thread1 = new Thread(
() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread1 finished");
}
);
Thread thread2 = new Thread(
() -> {
try {
thread1.join();
Thread.sleep(1000);
System.out.println("thread2 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
);
Thread thread3 = new Thread(
() -> {
try {
thread2.join();
System.out.println("thread3 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
);
thread3.start();
thread2.start();
thread1.start();
2 使用主线程的join方法
Thread thread1 = new Thread(
() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread1 finished");
}
);
Thread thread2 = new Thread(
() -> {
try {
thread1.join();
Thread.sleep(1000);
System.out.println("thread2 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
);
Thread thread3 = new Thread(
() -> {
try {
thread2.join();
System.out.println("thread3 finished");

最低0.47元/天 解锁文章
1171

被折叠的 条评论
为什么被折叠?



