Condition概述
Condition接口出现于Java1.5版本,用于取代Object类中的wait()方法与notify()方法,Condition接口相较于后者更为安全与高效
Conditon接口的await()方法 对应 Object类的wait()方法
Condition接口的signal()方法 对应 Object的类notify()方法
Condition接口中的signalAll()方法 对应 Object的类notifyAll()方法
Condition接口的使用依赖于Lock接口,创建Condition接口实现类的实例需要通过Lock接口实现类的实例
Condition condition = lock.newCondition()
Condition接口的方法,必须在同步代码块使用,即介于lock.lock()与lock.unlock()之间,否则在运行时会抛出IllegalMonitorStateException异常
示例代码
public class Test {
public static void main(String[] args) throws InterruptedException {
X x = new X();
//开启三个线程分别执行x1、x2、x3方法
new Thread(x::x1).start();
new Thread(x::x2).start();
new Thread(x::x3).start();
//确保前三个线程都被开启后 再开启第四个线程
TimeUnit.SECONDS.sleep(3);
//开启第四个线程唤醒执行x1方法的线程
new Thread(x::signalX1).start();
}
}
class X{
int num = 1;
Lock lock = new ReentrantLock();
Condition condition01 = lock.newCondition();
Condition condition02 = lock.newCondition();
Condition condition03 = lock.newCondition();
//唤醒执行x1方法的线程
public void signalX1(){
System.out.println("into signalX1");
lock.lock();
condition01.signal();
lock.unlock();
}
//执行x1、x2、x3方法的线程进入方法后都将阻塞 等待被唤醒
public void x1(){
System.out.println("into x1");
lock.lock();
try{
condition01.await();
System.out.println("x1");
condition02.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void x2(){
System.out.println("into x2");
lock.lock();
try{
condition02.await();
System.out.println("x2");
condition03.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void x3(){
System.out.println("into x3");
lock.lock();
try{
condition03.await();
System.out.println("x3");
condition01.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
运行效果
显然,执行x1、x2、x3方法的线程被依次唤醒