gpt4 book ai didi

java - 使用什么同步器进行线程初始化?

转载 作者:行者123 更新时间:2023-12-01 19:34:17 25 4
gpt4 key购买 nike

在开始使用线程之前,我们可以使用它来初始化线程的最佳同步器是什么?

public class Worker extends Thread {

private volatile boolean isAlive;

@Override
public void run() {
isAlive = true;
try {
do {
//doSomething
} while (true);
} finally {
isAlive = false;
}
}

public void waitForSomething() {
if (!isAlive) {
throw new IllegalStateException("Worker is not alive");
}
//something
}

public void waitForStartOfDoingSomething() {
//need to wait isAlive = true.
}
}

目前,上面的代码并不能保证方法waitForSomething在下一种情况下不会抛出IllegalStateException:

Worker worker = new Worker();
worker.start();
worker.waitForStartOfDoingSomething();
worker.waitForSomething();
//Then we let plenty of others threads to call worker.waitForSomething

我想保证上述情况下的 worker.waitForSomething() 永远不会抛出 IllegalStateException

最佳答案

您可能需要检查CountDownLatch为此目的。

private final CountDownLatch latch = new CountDownLatch(1);

public void run() {
try {
do {
//doSomething
} while (true);
} finally {
latch.countDown();
}
}

public void waitForSomething() throws InterruptedException {
latch.await();
//something
}

关于java - 使用什么同步器进行线程初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58410853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com