其实Lock的Condition中[await()/signal()]的作用和Synchronized中[wait()/notify()]的作用是一样的,只是使用的方法不一样.
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;/*** @Author Zhengzx* @Date 2023/10/17 17:37* @Title* @Version 1.0*/
public class ConditionTest01 {private Lock lock = new ReentrantLock();private Condition condition = lock.newCondition();public static void main(String[] args) throws InterruptedException {ConditionTest01 conditionTest01 = new ConditionTest01();conditionTest01.cal();Thread.sleep(3000);conditionTest01.signal();}public void signal() {try {lock.lock();//唤醒锁condition.signal();} catch (Exception e) {e.printStackTrace();}finally {lock.unlock();}}public void cal() {// Condition condition = lock.newCondition();new Thread(new Runnable() {@Overridepublic void run() {//主动释放锁 同时当前线程变为阻塞状态(注意:此处用到的是await()方法,不是wait()方法// 因为wait()是object()类中的, await()是Lock中的)try {lock.lock();//获取lock锁System.out.println("我是第一句话");condition.await();System.out.println("我是第二句话");} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}}).start();}}