gpt4 book ai didi

java - 在java中如何为多个线程创建通用进度指示器

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

如果我有 5 个正在工作的线程,当它们开始工作时,它们会发送一个进度启动命令,让进度轮开始旋转。当线程停止工作时,它会向轮子发送进度停止。

可以很容易地看出,这将不起作用,因为仍在工作的最后一个线程已被最后一个停止的线程删除了进度开始。

我正在考虑某种堆栈 fifo/lifo 实现来记住哪个线程正在做什么,然后正确地告诉进度轮它应该处于什么状态。

但是感觉它可能会被破坏,记住线程状态..

也许进度轮可以每 3 秒定期运行一个计时器,检查线程是否处于 Activity 状态有什么想法吗?

最佳答案

你可以做的一件事就是拥有一个 CountDownLatch。 CountDownLatch 的好处是,您可以将 ProgressWheel 作为一个新线程,主线程只会等待,直到计数器达到 0。每个 WorkerThread 都会在其构造函数中传递 CountDownLatch,并在运行时进行倒计时方法完成。

如果工作线程不是一次性启动的,则必须使用计数器,当线程完成时进行倒数,当一个线程启动时进行加数,并在进度轮中轮询其值。

这是一个示例代码

public static void main(String[] args) {
ProgressWheel wheel = new ProgressWheel();
CountDownLatch latch = new CountDownLatch(3);
wheel.start();
new WorkerThread(latch).start();
new WorkerThread(latch).start();
new WorkerThread(latch).start();
try {
latch.await(); //wait until counter reaches 0
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wheel.stop();

}

private static class WorkerThread extends Thread{
private CountDownLatch counter;
public WorkerThread(CountDownLatch counter) {
this.counter = counter;
}

@Override
public void run() {
//Do some heavy work
counter.countDown(); //This thread is finished
}
}

关于java - 在java中如何为多个线程创建通用进度指示器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48665875/

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