ReentrantLock 可以配合Condition来实现wait和notify的await()和signalAll()来实现线程的等待和唤醒。
示例代码:
public class TestClass {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private int count;
public void add() {
try {
lock.lock();
try {
for (int i = 0; i < 5; i++) {
count ++;
System.out.println("Test ReentrantLock "+Thread.currentThread()+" running");
System.out.println("Test ReentrantLock "+count);
if(count == 2){
condition.await();
}
}
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class MyClass {
public static void main(String[] args) {
final TestClass testClass = new TestClass();
new Thread(new Runnable() {
@Override
public void run() {
testClass.add();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
testClass.add();
}
}).start();
}
}
运行结果:
可以看到,Thread-0在输出2后停止了运行并由Thread-1继续运行下去