我正在尝试制作一个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) {
}
}
}
}
任何建议都会有很大帮助。
我已经看过几篇关于 SO 的文章,但我找不到任何与我的场景相匹配的东西,我可以轻松地实现它。
更新代码:-
我正在尝试下面的代码,但它在运行方法中的 catch 块上给了我错误。不确定我是否做错了什么。谁能帮我?
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) {
}
}
}
}