gpt4 book ai didi

java - 使用 java.util.concurrent API 结束线程

转载 作者:行者123 更新时间:2023-12-01 15:43:25 26 4
gpt4 key购买 nike

我正在使用线程,并决定使用最现代的 API(java.util.concurrent 包)。

这是我想要做的(伪代码):

//List of threads

private ScheduledExecutorService checkIns = Executors.newScheduledThreadPool(10);
//Runnable class

private class TestThread implements Runnable{
private int index = 0;
private long startTime = 0;
private long timeToExecute = 3000000;
public TestThread(int index){
this.index = index;
}

public void run(){
if(startTime == 0)
startTime = System.currentTimeMillis();
else if(startTime > (startTime+timeToExecute))
//End Thread
System.out.println("Execute thread with index->"+index);
}
}

//Cycle to create 3 threads
for(int i=0;i< 3; i++)
checkIns.scheduleWithFixedDelay(new TestThread(i+1),1, 3, TimeUnit.SECONDS);

我想在特定日期运行任务并重复它直到特定时间。时间过去后,任务结束。我唯一的问题是如何结束线程?

最佳答案

好吧,当任务不再执行时,您可以抛出异常,但这是相当残酷的替代方案:

  • 调度任务一次,让任务知道调度程序,这样它就可以在完成当前迭代时重新调度自己 - 但如果超过了最终时间,则立即返回。
  • 使用类似 Quartz Scheduler 的内容它更适合此类事情。

当然,第一个版本可以封装成更令人愉快的形式 - 您可以创建一个“SchedulingRunnable”,它知道何时运行子任务(提供给它)以及运行多长时间。

关于java - 使用 java.util.concurrent API 结束线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7610160/

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