Synchronize Is Blocking When I Try To CountDown

2019-07-23 08:03发布

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条回答
放荡不羁爱自由
2楼-- · 2019-07-23 08:24

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.

查看更多
登录 后发表回答