我使用 CountDownLatch遵循了我在这篇文章中找到的建议,但遇到了问题。我写了这个测试并运行它,当我尝试同步锁定时,我的线程创建了块。
private CountDownLatch lock = new CountDownLatch(1);
@Test
public void testBlock() {
Runnable r = new Runnable() {
@Override
public void run() {
try
{
synchronized(this) {
this.wait(50);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
throw (new RuntimeException(e));
}
releaseLock();
}
};
Thread t = new Thread(r);
t.setDaemon(true);
t.start();
waitOnCallback();
}
private void releaseLock() {
synchronized(lock) { // Thread t blocks here
lock.countDown();
}
}
private void waitOnCallback() {
synchronized(lock) {
try
{
lock.await();
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
}
为什么这不起作用?