gpt4 book ai didi

java - 在其他线程完成后调度周期性任务

转载 作者:行者123 更新时间:2023-12-01 18:58:49 24 4
gpt4 key购买 nike

我想要有 3 个线程同时执行一项任务,并且我想要一个线程在一段时间内执行计划任务(每 10 秒运行一次)。但我希望当 3 个线程完成时仅运行一次计划任务,然后我希望该线程终止。实现这些线程的最佳方法是什么? ExecutorService接口(interface)是否适合这个?

最佳答案

这是我刚刚编写的示例:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class Example {

public static void main(String[] args) throws InterruptedException {
ScheduledFuture future = Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new MyScheduledTask(), 0, 10, TimeUnit.SECONDS);
ExecutorService executor = Executors.newFixedThreadPool(3); // pool composed of 3 threads
for (int i = 0; i < 3; i++) {
// for the example assuming that the 3 threads execute the same task.
executor.execute(new AnyTask());
}
// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();
// expect current thread to wait for the ending of the 3 threads
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.TimeUnit.NANOSECONDS);
future.cancel(false); // to exit properly the scheduled task
// reprocessing the scheduled task only one time as expected
new Thread(new ScheduledTask()).start();

}


}

class MyScheduledTask implements Runnable {
@Override
public void run() {
//Process scheduled task here
}
}

class AnyTask implements Runnable {
@Override
public void run() {
//Process job of threads here
}
}

关于java - 在其他线程完成后调度周期性任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13041708/

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