等到另一个线程获取锁定

时间:2018-03-19 09:20:07

标签: java multithreading concurrency

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

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

with open('49359186.txt', 'r') as input:

    topics = {}
    currentTitle = ''

    for line in input:
        line = line.rstrip()
        if line[0] != ' ':
            currentTitle = line
            topics[currentTitle] = []
        else:
            topics[currentTitle].append(line)

print topics

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

1 个答案:

答案 0 :(得分:5)

使用CountDownLatch

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

//do not continue until the latch has counted down to zero.
latch.await();
continueWithOtherStuffThatAlsoAcquiresALockAtSomePointInTime()

然后:

{{1}}