gpt4 book ai didi

java - 如何将线程加入线程池中的主线程?

转载 作者:行者123 更新时间:2023-11-30 03:50:45 25 4
gpt4 key购买 nike

我正在使用线程池在不同的进程中运行任务,将所有线程连接到主线程,我正在这样做,但需要更多时间才能给出结果。如何以有效的方式实现这一点。

        ExecutorService executor = Executors.newFixedThreadPool(2);
Runnable sendded = new com.treamis.hr.employee.Sendded(filePath, academicyearmaster);
executor.execute(sendded);

Runnable employeeAttendanceReport = new EmployeeAttendanceReport(filePath2);
executor.execute(employeeAttendanceReport);
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");

最佳答案

我将使用 Future 来完成此任务。使用 executor.submit(yourrunnable) 而不是 executor.execute(yourrunnable),它将返回一个 Future。当您在主线程中以某种方式重用这些 future 对象时,它将必须等到所有线程都完成为止。

[编辑]这是一个示例:

Future future = executorService.submit(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
});

future.get(); //returns null if the task has finished correctly.

(取自 http://tutorials.jenkov.com/java-util-concurrent/executorservice.html )

关于java - 如何将线程加入线程池中的主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24509420/

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