problem description
when using Condition to suspend and wake up threads, I often see the following methods
Thread1 calling the Await () method to wait for Thread2"s Signal to wake up. In order to avoid a long wait and add a timeout limit, Thread1 is usually written as Condition.await (long,TimeUnit). But is it true that Condition will return after the timeout?
the environmental background of the problems and what methods you have tried
I looked through the relevant source code and found that this is not the case. You can detect
with the following coderelated codes
/ / Please paste the code text below (do not replace the code with pictures)
public class TestConditionAwait {
private static ReentrantLock lock = new ReentrantLock();
private static Logger Log = LoggerFactory.getLogger(TestConditionAwait.class);
public static void main(String[] args) throws InterruptedException {
final Condition condition = lock.newCondition();
final Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
Thread.currentThread().setName("ConditionAwait-Thread-");
Log.error(Thread.currentThread().getName() + " beforeAwaitTime:" + System.currentTimeMillis());
condition.await(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.error(Thread.currentThread().getName() + " finishAwaitTime:" + System.currentTimeMillis());
}finally {
lock.unlock();
Log.error(Thread.currentThread().getName() + " unlockTime:" + System.currentTimeMillis());
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("ConditionSignal-Thread-");
try{
Log.error(Thread.currentThread().getName() + " getLockTime:" + System.currentTimeMillis());
thread1.interrupt();
lock.lock();
long currentTime = System.currentTimeMillis();
while (System.currentTimeMillis() - currentTime < 8000){
}
condition.signal();
Log.error(Thread.currentThread().getName() + " signalTime:" + System.currentTimeMillis());
}catch (Exception e){
}finally {
lock.unlock();
Log.error(Thread.currentThread().getName() + " unlockTime:" + System.currentTimeMillis());
}
}
});
thread1.start();
Thread.sleep(50);
thread2.start();
}
}