gpt4 book ai didi

java - ExecutorService、Future、Threads 当所有 Runnables 必须完成时出现 Actives

转载 作者:行者123 更新时间:2023-12-02 00:22:55 24 4
gpt4 key购买 nike

我有一个复杂的程序,使用 Runnable、ExecutorService 和 Future。

我想知道为什么 Runnable/Threads 看起来正在运行,而我的应用程序仍在运行,而我希望所有这些都必须完成。

完整代码您可以复制粘贴,然后运行,您需要的一切都在这里。

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TestFutureExecutorService {

public static void main(String... args) {

List<Future<?>> futureList = new ArrayList<>();
ExecutorService executorService = Executors.newCachedThreadPool();

RunnableTest rt = new RunnableTest("rt", futureList, executorService);

new Timer(false).schedule(new TimerTask() {
@Override
public void run() {
rt.stop();
}
}, ThreadLocalRandom.current().nextLong(100L, 500L));

System.out.println("Let's go to check the threads status.\n");
for (int i = 0; i < futureList.size(); i++) {//Working!
try {
if (futureList.get(i) != null) {
futureList.get(i).get();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
System.out.println("Apparently everything is finished.\n");

boolean allDone = true;
for (int i = 0; i < futureList.size(); i++) {
if (futureList.get(i) != null) {
allDone &= futureList.get(i).isDone(); // check if future is done
}

}
System.out.println("Is everything really finished?:" + allDone + ".\n");
//executorService.shutdown();

Thread thisThread = Thread.currentThread();
thisThread.setName("Admin Thread");
thisThread.setPriority(1);
System.out.println("Thread = " + thisThread);

int count = Thread.activeCount();
System.out.println("currently active threads = " + count);

Thread activeThreadsArray[] = new Thread[count];
Thread.enumerate(activeThreadsArray);
// prints active threads
for (int i = 0; i < count; i++) {
System.out.println(i + ": " + activeThreadsArray[i]);
}

}

public static class RunnableTest implements Runnable {
private final String name;
private final List<Future<?>> futureList;
private final ExecutorService executorService;
private volatile boolean isRunning = false;

public RunnableTest(String name, List<Future<?>> futureList, ExecutorService executorService) {
this.name = name;
this.futureList = futureList;
this.executorService = executorService;
this.futureList.add(this.executorService.submit(this));
}

@Override
public void run() {
Thread.currentThread().setName(Thread.currentThread().getName() + this.getClass().getSimpleName() + ":" + name);
isRunning = true;
while (isRunning) {
try {
Thread.sleep(50);
new Processor(this.futureList, this.executorService);
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("Finishing:" + Thread.currentThread().getName());
}

public void stop() {
isRunning = false;
}

}

public static class Processor implements Runnable {

private final List<Future<?>> futureList;
private final ExecutorService executorService;

public Processor(List<Future<?>> futureList, ExecutorService executorService) {
this.futureList = futureList;
this.executorService = executorService;
this.futureList.add(this.executorService.submit(this));
}

@Override
public void run() {
String hour = new SimpleDateFormat("_yyyyMMdd-HHmmss.SSSS_").format(new Date());
Thread.currentThread().setName(hour + this.getClass().getSimpleName());
try {
int timeSleeping = ThreadLocalRandom.current().nextInt(100, 300);
Thread.sleep(timeSleeping);
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Finishing:" + Thread.currentThread().getName());
}
}

}

现在,输出......

Let's go to check the threads status.

Finishing:_20190923-203808.0435_Processor
Finishing:_20190923-203808.0437_Processor
Finishing:_20190923-203808.0489_Processor
Finishing:pool-1-thread-1->RunnableTest:rt
Finishing:_20190923-203808.0695_Processor
Finishing:_20190923-203808.0544_Processor
Finishing:_20190923-203808.0593_Processor
Finishing:_20190923-203808.0746_Processor
Finishing:_20190923-203808.0645_Processor
Apparently everything is finished.

Is everything really finished?:true.

Thread = Thread[Admin Thread,1,main]
currently active threads = 8
0: Thread[Admin Thread,1,main]
1: Thread[pool-1-thread-1->RunnableTest:rt,5,main]
2: Thread[Timer-0,5,main]
3: Thread[_20190923-203808.0593_Processor,5,main]
4: Thread[_20190923-203808.0695_Processor,5,main]
5: Thread[_20190923-203808.0746_Processor,5,main]
6: Thread[_20190923-203808.0544_Processor,5,main]
7: Thread[_20190923-203808.0645_Processor,5,main]

当我运行应用程序时,在我的 IDE 中,保持“正在运行”的状态,但所有可运行的都必须完成!

为什么线程显示为 Activity 状态? 这意味着什么?

如何完成这一切?

最佳答案

您正在使用ExecutorService。 ExecutorService 使线程保持 Activity 状态,为下一个任务做好准备。您必须告诉 ExecutorService 您不再有任务,它可以丢弃线程。

您可以通过调用方法来做到这一点

 `shutdown() or shutdownNow()`

因此,完成检查后取消代码中的行注释:

 System.out.println("Is everything really finished?:" + allDone + ".\n");
//executorService.shutdown();

您的应用程序仍然无法完成,因为您将计时器线程创建为非守护线程,这意味着如果应用程序中存在正在运行的非守护线程,JVM 将不会停止。

您可以将计时器创建为守护线程,如下所示:

new Timer(true).schedule(new TimerTask() {

关于java - ExecutorService、Future、Threads 当所有 Runnables 必须完成时出现 Actives,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58071424/

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