我试图在获得锁的同时解决并发问题,代码如下所示:
线程启动后立即获取实锁,这已经为时已晚。
acquireLockAndRunOnNewThread(() -> {
acquiredLock=true;
continueWithOtherStuff();
}
//do not continue until the lock is acquired
while(acquiredLock==false){
Thread.sleep(100);
}
continueWithOtherStuffThatAlsoAcquiresALockAtSomePointInTime()
没有thread.sleep,如何正确解决此问题?
最佳答案
CountDownLatch latch = new CountDownLatch(1);
然后:
acquireLockAndRunOnNewThread(() -> {
latch.countDown();
continueWithOtherStuff();
}
//do not continue until the latch has counted down to zero.
latch.await();
continueWithOtherStuffThatAlsoAcquiresALockAtSomePointInTime()