gpt4 book ai didi

java - ScheduledThreadPoolExecutor 线程在完成后仍保留

转载 作者:行者123 更新时间:2023-11-30 05:50:00 24 4
gpt4 key购买 nike

例程 myProcessToRun() 需要执行 100 次,但每次执行之间需要大约一秒钟的延迟。

以下 FOR 循环与 ScheduledThreadPoolExecutor 对象结合使用。

for (int n=0; n<100; n++)
{
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.schedule(new Runnable() {
@Override
public void run() {
myProcessToRun();
}
}, (n+2), TimeUnit.SECONDS);
}

这实际上工作正常,但线程仍然存在。使用 JVisualVM,执行例程时线程数会增加 100 个线程。当例程完成时,100 个线程仍然存在。

单击“执行 GC”按钮不会清除它们,因此 Java 仍然认为它们应该存在。

如何使用上面的示例清理这些线程?

---已编辑---

我注意到 ScheduledThreadPoolExecutor 正在循环中实例化,这是一个糟糕的主意。将其移出循环之后,创建的线程并没有那么糟糕。

尝试实现该解决方案后,出现了意外行为。

final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);               
for (int n=0; n<100; n++)
{
//final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
executor.schedule(new Runnable() {
@Override
public void run() {
doAddNewCondSet();
}
}, (n+2), TimeUnit.SECONDS);
}
try
{
executor.shutdown();
if (!executor.awaitTermination(400, TimeUnit.SECONDS))
executor.shutdownNow();
} catch (InterruptedException e1)
{
e1.printStackTrace();
}

使用修改后的代码,它将立即停止所有进程并关闭,并且不会执行任何操作。使用 executor.shutdown();注释掉并仅使用awaitTermination(),程序就挂起,几分钟后,所有进程同时启动,没有延迟,从而导致错误。

我怀疑我的实现是错误的。

最佳答案

有多种方法可以实现此目的。您可以在这里查看其中一些: https://www.baeldung.com/java-executor-wait-for-threads

我个人最喜欢的是 CountDownLatch:

Next, let’s look at another approach to solving this problem – using a CountDownLatch to signal the completion of a task.

We can initialize it with a value that represents the number of times it can be decremented before all threads, that have called the await() method, are notified.

For example, if we need the current thread to wait for another N threads to finish their execution, we can initialize the latch using N:

ExecutorService WORKER_THREAD_POOL 
= Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
WORKER_THREAD_POOL.submit(() -> {
try {
// ...
latch.countDown();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}

// wait for the latch to be decremented by the two remaining threads
latch.await();

关于java - ScheduledThreadPoolExecutor 线程在完成后仍保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54093472/

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