等到另一个线程获取锁定

Ari*_*Ari 1 java concurrency multithreading

我试图在获得锁定时解决并发问题,代码如下所示:

一旦线程启动就会获得真正的锁定,这已经太晚了.

acquireLockAndRunOnNewThread(() -> {
    acquiredLock=true;
    continueWithOtherStuff();
}

//do not continue until the lock is acquired
while(acquiredLock==false){
    Thread.sleep(100); 
}
continueWithOtherStuffThatAlsoAcquiresALockAtSomePointInTime()
Run Code Online (Sandbox Code Playgroud)

如果没有thread.sleep,我怎样才能正确解决这个问题?

And*_*ner 5

使用CountDownLatch:

CountDownLatch latch = new CountDownLatch(1);
Run Code Online (Sandbox Code Playgroud)

然后:

acquireLockAndRunOnNewThread(() -> {
    latch.countDown();
    continueWithOtherStuff();
}

//do not continue until the latch has counted down to zero.
latch.await();
continueWithOtherStuffThatAlsoAcquiresALockAtSomePointInTime()
Run Code Online (Sandbox Code Playgroud)