我只是想在主线程中等待,直到运行中的某个事件.我怎么能用java.util.concurency类来做呢?谢谢!
PS我的问题是否真的解释不好,正确性检查是不是很糟糕?我的意思是这个消息"哎呀!你的问题无法提交,因为:
你的帖子没有太多的上下文来解释代码部分; 请更清楚地解释你的情景."?
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 (InterruptedException e) {}
initLock.unlock();
}
});
th.start();
try {
condition.await(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {}
long t2= System.currentTimeMillis();
System.out.println(t2-t1);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1299 次 |
| 最近记录: |