同步阻塞当我尝试CountDown [英] Synchronize Is Blocking When I Try To CountDown
本文介绍了同步阻塞当我尝试CountDown的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我关注了我在此信息中发现的建议使用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();
}
};
线程t =新线程(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);
}
}
}
?CountDownLatch不是一个需要同步的对象(例如,删除 synchronized(),锁)
块)。所有线程安全性都在对象本身内部处理。
I followed the advice I found in this post using CountDownLatch and i'm running into a problem. I wrote up this test and ran it and my thread I created blocks when i try to synchronize on lock.
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);
}
}
}
Why isn't this working?
解决方案
A CountDownLatch is not an object on which you need to synchronize (i.e. remove the synchronized(lock)
blocks). all thread-safety is handled internally to the object itself.
这篇关于同步阻塞当我尝试CountDown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文