我使用CountDownLatch跟踪the advice I found in this post,我遇到了问题。我编写了这个测试并运行它,我的线程在我尝试同步锁定时创建了块。
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);
}
}
}
为什么这不起作用?
答案 0 :(得分:2)
CountDownLatch不是您需要同步的对象(即删除synchronized(lock)
块)。所有线程安全都在内部处理对象本身。