wait/notify
package com.kang.multithread;
/**
* @author klr
* @create 2020-09-16-10:53
*/
public class Print21 {
static final Object lock = new Object();
static boolean con = false;
public static void main(String[] args) {
new Thread(()->{
synchronized (lock) {
while (!con) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(1);
}
},"t1").start();
new Thread(()->{
synchronized (lock) {
System.out.println(2);
con = true;
lock.notify();
}
},"t2").start();
}
}
park/unpark
package com.kang.multithread;
import java.util.concurrent.locks.LockSupport;
/**
* @author klr
* @create 2020-09-16-10:53
*/
public class Print21 {
static final Object lock = new Object();
static boolean con = false;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
// synchronized (lock) {
// while (!con) {
// try {
// lock.wait();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
LockSupport.park();
System.out.println(1);
// }
}, "t1");
t1.start();
new Thread(()->{
// synchronized (lock) {
// System.out.println(2);
// con = true;
// lock.notify();
// }
System.out.println(2);
LockSupport.unpark(t1);
},"t2").start();
}
}
网友评论