How to lock in one thread and wait until lock will be released in another thread
I just want wait in main thread until some event in run. How can I do it using java.util.concurency classes? Thanks!
P.S. Does my question realy explained bad o correctness check is shit? I mean this message "Oops! Your question couldn't be submitted because:
Your post does not have much context to explain the code sections; please explain your scenario more clearly."?
public class LockingTest {
private Lock initLock = new ReentrantLock();
@Test
public void waiting(){
initLock.lock();
final Condition condition = initLock.newCondition();
long t1= System.currentTimeMillis();
Thread th = new Thread(new Runnable(){
@Override public void run() {
try {
Thread.currentThread().sleep(2000);
} catch (Interrupted开发者_StackOverflowException e) {}
initLock.unlock();
}
});
th.start();
try {
condition.await(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {}
long t2= System.currentTimeMillis();
System.out.println(t2-t1);
}
}
you can use CountDownLatch( http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html ).
1. init countdownlatch with count value 1
2. start another thread (Thread A )
3. call await() in main thread
4. call countdown() in Thread A
精彩评论