【发布时间】:2018-04-09 06:46:32
【问题描述】:
我在这里和那里看到了我的答案的一部分,但不是完整的。
我知道如果你想同时运行多个任务,你想使用 Thread 和 Runnable 实现
我看到如果你想运行这样的重复性任务,你可以使用ScheduledExecutorService:
Runnable helloRunnable = () -> System.out.println("Hello world " + LocalDateTime.now().toLocalTime().toString());
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 10, TimeUnit.SECONDS);
但这只是运行一个线程,并且没有方法或参数在一定时间后杀死进程
我想做的是每 10 秒并行运行 5 次相同的任务,持续 10 分钟
编辑
如果未来的人对这里的完整示例感兴趣,那就是:
public static void main(String[] args) {
Runnable helloRunnable = () -> System.out.println("Hello world " + LocalDateTime.now().toLocalTime().toString());
Runnable testRunnable = () -> System.out.println("Test runnable " + LocalDateTime.now().toLocalTime().toString());
List<Runnable> taskList = new ArrayList<>();
taskList.add(helloRunnable);
taskList.add(testRunnable);
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
List <ScheduledFuture<?>> promiseList = new ArrayList<>();
for (Runnable runnable : taskList) {
ScheduledFuture<?> promise = executor.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
promiseList.add(promise);
}
List <Runnable> cancelList = new ArrayList<>();
for (ScheduledFuture<?> promise : promiseList) {
Runnable cancelRunnable = () -> {
promise.cancel(false);
executor.shutdown();
};
cancelList.add(cancelRunnable);
}
List <ScheduledFuture<?>> canceledList = new ArrayList<>();
for (Runnable runnable : cancelList){
ScheduledFuture<?> canceled = executor.schedule(runnable, 10, TimeUnit.SECONDS);
canceledList.add(canceled);
}
}
【问题讨论】:
标签: java multithreading runnable scheduledexecutorservice