虽然可以使用object的wait、notify,也仍然是很多人的选择;但是不便于把一组相关联的条件封装在一起。
用Lock和Condition则可以实现.
Lock relaLock = new ReentrantLock();
Condition relaCondition1 = relaLock.newCondition();
Condition relaCondition2 = relaLock.newCondition();
Thread thread1 = new Thread(() -> {
long i = 0;
while (i++ < Long.MAX_VALUE) {
if (i % 100000000 != 0) {
continue;
}
System.out.println(“thread1 i:” + (i / 100000000));
if (i / 100000000 < 10) {//not wait condition
continue;
}
try {
relaLock.lock();
relaCondition1.await();
i=0;
} catch (InterruptedException ex) {
System.out.println(“thread flag:” + Thread.currentThread().isInterrupted());
} finally {
relaLock.unlock();
}
}
});
thread1.start();
Thread.sleep(10000L);
try {
relaLock.lock();
System.out.println(“relaCondition1 signal”);
relaCondition1.signalAll();
}finally {
relaLock.unlock();
}
thread1.join();
输出
thread1 i:1
thread1 i:2
thread1 i:3
thread1 i:4
thread1 i:5
thread1 i:6
thread1 i:7
thread1 i:8
thread1 i:9
thread1 i:10
relaCondition1 signal
thread1 i:1
thread1 i:2
thread1 i:3
thread1 i:4