借助wait和notify方法控制线程以固定的顺序执行:
/**
* 控制输出字符的顺序,必须是固定顺序2,1
* 采用wait-notify实现
* @param args
*/
public static void main(String[] args) {
new Thread(() -> {
synchronized (lock) {
while (!isPrint2) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info("1");
}
}, "t1").start();
new Thread(() -> {
synchronized (lock) {
log.info("2");
isPrint2 = true;
lock.notify();
}
}, "t2").start();
}
}
借助park和unpark方法控制线程以固定的顺序执行:
@Slf4j
public class ParkOrderDemo {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
LockSupport.park();
log.info("1");
}, "t1");
t1.start();
new Thread(() -> {
log.info("2");
LockSupport.unpark(t1);
}, "t2").start();
}
}