1. 指定线程执行顺序
可以使用join()方法(但中间加了Thread.sleep(1000)以后就不按顺序执行,不知道为什么)
public static void main(String[] args) throws CloneNotSupportedException {
// 创建线程对象
Thread t1 = new Thread(() -> {
System.out.println("t1");
});
Thread t2 = new Thread(() -> {
try {
t1.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("t2");
});
Thread t3 = new Thread(() -> {
try {
t2.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("t3");
});
// 启动线程,启动顺序无所谓,因为有join的约束
t3.start();
t2.start();
t1.start();
}
2.使用LOCK.wait()和LOCK.notify()
public static void main(String[] args) throws CloneNotSupportedException, InterruptedException {
Object LOCK = new Object();
Thread t1 = new Thread(() -> {
System.out.println("t1");
synchronized (LOCK) {
LOCK.notify();
}
});
Thread t2 = new Thread(() -> {
try {
synchronized (LOCK) {
LOCK.wait();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("t2");
});
t2.start();
Thread.sleep(1000);
t1.start();
}