今天来看看一个比较有意思的东西:
有三个线程,线程名称分别为:a,b,c。
每个线程打印自己的名称。
需要让他们同时启动,并按 c,b,a的顺序打印
方法一:可以在创建线程的时候就调用join()方法,确保我们的线程可以按照心想的顺序去执行
public class Demo21 {
public static void main(String[] args) throws InterruptedException {
MyThread1 myThread = new MyThread1();
Thread a = new Thread(myThread,"a");
Thread b = new Thread(myThread,"b");
Thread c = new Thread(myThread,"c");
c.start();
c.join();
b.start();
b.join();
a.start();
a.join();
}
}
class MyThread1 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
方法二:同样是使用join()方法,不过可以在创建线程的时候一环套一环来确保线程的执行顺序,俗称套娃
public class Thread_2152 {
public static void main(String[] args) throws InterruptedException {
// 创建三个线程
Thread tc = new Thread(() -> {
// 打印c
System.out.print(Thread.currentThread().getName() + " ");
}, "c");
Thread tb = new Thread(() -> {
try {
// 等待c 执行完成
tc.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 打印b
System.out.print(Thread.currentThread().getName() + " ");
}, "b");
Thread ta = new Thread(() -> {
try {
// 等待b 执行完成
tb.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 打印a
System.out.print(Thread.currentThread().getName() + " ");
}, "a");
// 需要让他们同时启动,并按 c,b,a的顺序打印
ta.start();
tb.start();
tc.start();
}
}