1.用wait和notify实现
package com.learning.thread_order;
/**
* @Author wangyouhui
* @Description 线程顺序执行
**/
public class ThreadOrderExecute {
private static boolean flag = false;
private static final Object lock = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(()->{
synchronized (lock){
while(!flag){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程1执行");
}
}, "线程1");
Thread thread2 = new Thread(()->{
synchronized (lock){
System.out.println("线程2执行");
flag = true;
lock.notify();
}
}, "线程2");
thread1.start();
thread2.start();
}
}
2.用park和unpark实现
package com.learning.thread_order;
import java.util.concurrent.locks.LockSupport;
/**
* @Author wangyouhui
* @Description 利用park实现线程顺序执行
**/
public class ThreadOrderExecute3 {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
LockSupport.park();
System.out.println("线程1执行");
});
Thread t2 = new Thread(() -> {
System.out.println("线程2执行");
LockSupport.unpark(t1);
});
t1.start();
t2.start();
}
}