jdk 官网对Condition的描述:
Condition 将 Object 监视器方法(wait
、notify
和 notifyAll
)分解成截然不同的对象,以便通过将这些对象与任意 Lock
实现组合使用,为每个对象提供多个等待 set (wait-set)。其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。
下面通过网上一道面试题看看Condition的应用:
启动三个线程,顺序打印ABC十次
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class PrintABC {
Lock lock = new ReentrantLock();
Condition aCdt = lock.newCondition();
Condition bCdt = lock.newCondition();
Condition cCdt = lock.newCondition();
int order = 0;
public static void main(String[] args) {
final PrintABC print = new PrintABC();
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
print.printA();
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
print.printB();
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
print.printC();
}
});
}
executorService.shutdown();
}
public void printA() {
try {
lock.lock();
while (order != 0) {
aCdt.await();
}
System.out.println("A");
order = 1;
bCdt.signal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB() {
try {
lock.lock();
while (order != 1)
bCdt.await();
System.out.println("B");
order = 2;
cCdt.signal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC() {
try {
lock.lock();
while (order != 2)
cCdt.await();
System.out.println("C");
order = 0;
aCdt.signal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.unlock();
}
}
}