1. Object wait和notify实现等待与唤醒
没有锁会报错。
public class demo01 {
public static void main(String[] args) {
Object objectLock = new Object();
new Thread(()->{
synchronized (objectLock) {
try {
// 释放当前锁, 等待notify, 必须先使用wait才能使用notify
objectLock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Thread 1");
}
}).start();
new Thread(()->{
synchronized (objectLock) {
System.out.println("Thread 2");
objectLock.notify();
}
}).start();
}
}
2. Lock.newCondition await和signal实现等待与唤醒
public class demo02 {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
new Thread(()->{
lock.lock();
try {
// 释放锁并等待通知
condition.await();
System.out.println("Thread 1");
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}).start();
new Thread(()->{
lock.lock();
System.out.println("Thread 2");
condition.signal();
lock.unlock();
}).start();
}
}
3. LockSupport park和unpark实现等待与唤醒
unpark只能产生一个permit,且可以提前产生,
public class demo03 {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// 可以先进行 unpark, 并且 permit 只能有一个
// 需要两个permit
LockSupport.park();
LockSupport.park();
System.out.println("Thread1");
});
thread.start();
new Thread(()->{
System.out.println("Thread 2");
// 只会产生一个permit
LockSupport.unpark(thread);
LockSupport.unpark(thread);
}).start();
}
}