ReentrantLock、Condition结合使用实现多线程通讯

package maptoxml;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class SemaphoreTest {
static volatile private ReentrantLock lock = new ReentrantLock();
static volatile private Condition condition = lock.newCondition();
static volatile private Boolean isWait = false;

private static void test() throws InterruptedException {
lock.lock();// 只有一个线程可以执行下面的代码
if (!isWait) {
System.out.println(Thread.currentThread().getName() + "进入了等待");
isWait = true;
condition.await();
System.out.println(Thread.currentThread().getName() + "被唤醒");
} else {
isWait = false;
condition.signalAll();
System.out.println(Thread.currentThread().getName() + "唤醒了所有的线程");
}
lock.unlock();
}

public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 2; i++) {// 开启两个线程
executorService.execute(new Runnable() {
@Override
public void run() {
try {
test();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}