利用Java线程工具类LockSupport
LockSupport.pack()//阻塞当前线程
LockSupport.unpack()//指定线程解除阻塞
解答如下
static Thread t1, t2;
public static void main(String[] args) {
t1 = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
LockSupport.unpark(t2);
LockSupport.park();
}
});
t2 = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
LockSupport.park();
System.out.println(i);
LockSupport.unpark(t1);
}
});
t1.start();
t2.start();
}
评论区