我正在尝试进行ExecutorService
实现,可以为每个线程提供超时或中断。
在我的下面示例中,假设我正在生成2 threads
(在实际情况下,此数字会很高),然后我需要确保each thread
应该为10 minutes
运行。
这意味着,Thread1 will run for 10 minutes
和Thread2 will run for 10 minutes as well
。如果10分钟结束,那么我需要中断线程或超时。
以下是我到目前为止的代码,我无法理解如何以这种干净的方式在此处添加此interrupt or timeout
功能,以便我可以在no of threads
参数中配置此public static void main(String[] args) {
final int noOfThreads = 2;
final long exp_time_millis = 600000; //10 minutes
//create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
for (int i = 0, i< noOfThreads; i++) {
service.submit(new ThreadTask());
}
}
class ThreadTask implements Runnable {
@Override
public void run() {
while(true) {
System.out.println("Thread running...");
try {
/* make a select sql to the database
* and measure how much time it is taking in
* returning the response
*/
} catch (InterruptedException e) {
}
}
}
}
参数我的代码然后它也应该在那里正常工作。
public class ThreadTimeout {
public static void main(String[] args) {
final int noOfThreads = 2;
//create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
ScheduledExecutorService scheduleService = Executors.newScheduledThreadPool(noOfThreads);
for (int i = 0; i< noOfThreads; i++) {
final Future future = service.submit(new ThreadTask());
scheduleService.schedule(new Runnable(){
public void run(){
future.cancel(true);
}
}, 10, TimeUnit.MINUTES);
}
}
}
class ThreadTask implements Runnable {
@Override
public void run() {
//make a database connection
while (true) {
System.out.println("Thread running...");
try {
/*
* make a select sql to the database and measure
* how much time it is taking in returning the
* response
*/
} catch (InterruptedException e) {
}
}
}
}
任何建议都会有很大的帮助。
我已经看过很少关于SO的文章,但我找不到任何符合我情景的文章,我可以轻松实现。
更新代码: -
我正在尝试以下代码,但它在run方法中的catch块上给出了错误。不确定我做错了什么。任何人都可以帮助我吗?
{{1}}
答案 0 :(得分:1)
我建议使用第二个ScheduledExecutorService
。您可以将原始提交内容中返回的Future
提交至ScheduledExecutorService
以取消。
ScheduledExecutorService scheduleService = Executors.newScheduledThreadPool(n);
for (int i = 0, i< noOfThreads; i++) {
final Future future = service.submit(new ThreadTask());
scheduleService.schedule(new Runnable(){
public void run(){
future.cancel(true);
}
}, 10, TimeUnits.MINUTES);
}
现在ThreadTask
需要响应中断,否则这无济于事。
答案 1 :(得分:0)
我建议使用ExecutorService.awaitTermination(...);
方法,然后使用ExecutorService.shutdownNow()
方法。
例如:
for (int i = 0; i < noOfThreads; i++) {
service.submit(new ThreadTask());
}
// we always need to shutdown the service _after_ we've submitted all jobs
service.shutdown();
// now we wait for those tasks to finish for 10 minutes
if (!service.awaitTermination(10, TimeUnit.MINUTES)) {
// if we timed out waiting for the tasks to finish, forcefully interrupt them
service.shutdownNow();
}
请注意,这会中断线程,但这只会导致某些方法,例如Thread.sleep()
,Object.wait()
和其他一些方法抛出InterruptedException
。它还设置线程上的中断位,可以使用Thread.currentThread().isInterrupted()
进行测试。它将不“杀死”线程,就像你使用unix进程一样。