Condition 类的 awiat 方法和 Object 类的 wait 方法等效
Condition 类的 signal 方法和 Object 类的 notify 方法等效
Condition 类的 signalAll 方法和 Object 类的 notifyAll 方法等效
ReentrantLock 类可以唤醒指定条件的线程,而 object 的唤醒是随机的
synchronized方式对比下
public static Student student = null;
public static void waitTest() throws InterruptedException {
student = new Student();
Thread t1 = new Thread(() -> {
synchronized (student) {
System.out.println("t1 wait!");
try {
student.wait();
System.out.println("t1 开始重新run!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
Thread.sleep(3000);
Thread t2 = new Thread(() -> {
synchronized (student) {
System.out.println("t2 我通知了 notify!");
student.notify();
}
});
t2.start();
}
Condition实现方式
public static ReentrantLock lock = new ReentrantLock();
public static Condition condition = lock.newCondition();
private static void reentrantLock() throws InterruptedException {
Thread t1 = new Thread(() -> {
lock.lock();
try {
System.out.println("我进入了T1!");
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
System.out.println("释放T1锁!");
}
});
t1.start();
Thread.sleep(2000);
Thread t2 = new Thread(() -> {
lock.lock();
try {
System.out.println("我进入了T2!");
condition.signal();
System.out.println("我是T2,我唤醒了T1,T1进入等待状态!");
//condition.signalAll();
} finally {
lock.unlock();
System.out.println("释放T2锁!");
}
});
t2.start();
}