Synchronize Is Blocking When I Try To CountDown

杀马特。学长 韩版系。学妹 提交于 2019-12-24 11:17:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/11007551/synchronize-is-blocking-when-i-try-to-countdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!