Java 每个线程应运行10分钟,然后在时间结束时中断线程

Java 每个线程应运行10分钟,然后在时间结束时中断线程,java,multithreading,executorservice,Java,Multithreading,Executorservice,我试图创建一个ExecutorService实现,可以为每个线程提供超时或中断 在下面的示例中,假设我正在生成2个线程(在实际场景中,这个数字会很高),那么我需要确保每个线程都应该运行10分钟。 这意味着,Thread1将运行10分钟,而Thread2也将运行10分钟。如果10分钟过去了,那么我需要中断线程或超时 下面是我到目前为止的代码,我无法理解如何以如此干净的方式在这里添加此中断或超时功能,以便如果我在代码中配置此线程数参数,那么它也应该正常工作 public static void ma

我试图创建一个
ExecutorService
实现,可以为每个线程提供超时或中断

在下面的示例中,假设我正在生成
2个线程
(在实际场景中,这个数字会很高),那么我需要确保
每个线程
都应该运行
10分钟
。 这意味着,
Thread1将运行10分钟
,而
Thread2也将运行10分钟
。如果10分钟过去了,那么我需要中断线程或超时

下面是我到目前为止的代码,我无法理解如何以如此干净的方式在这里添加此
中断或超时
功能,以便如果我在代码中配置此
线程数
参数,那么它也应该正常工作

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) {

            }
        }
    }
}
publicstaticvoidmain(字符串[]args){
最终int noOfThreads=2;
最终长时间扩展时间=600000;//10分钟
//创建具有给定大小的线程池
ExecutorService=Executors.newFixedThreadPool(noOfThreads);
对于(inti=0,i
任何建议都会大有帮助

我已经看过一些关于SO的文章,但是我找不到任何与我的场景相匹配的东西,我可以很容易地实现它

更新代码:-

我正在尝试下面的代码,但它在run方法中的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) {

            }
        }
    }
}
公共类线程超时{
公共静态void main(字符串[]args){
最终int noOfThreads=2;
//创建具有给定大小的线程池
ExecutorService=Executors.newFixedThreadPool(noOfThreads);
ScheduledExecutorService scheduleService=Executors.newScheduledThreadPool(noOfThreads);
for(inti=0;i
我建议使用
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();
}
for(inti=0;i

请注意,这将中断线程,但这只会导致某些方法,如
Thread.sleep()
Object.wait()
,以及其他一些方法引发
中断异常。它还设置线程上的中断位,可使用
thread.currentThread().isInterrupted()
对其进行测试。它不会像unix进程那样“杀死”线程。

我建议使用第二个
ScheduledExecutorService
。您可以将原始提交返回的
未来
提交到
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);
}
ScheduledExecutorService scheduleService=Executors.newScheduledThreadPool(n);
对于(inti=0,i

现在,
ThreadTask
需要对中断做出响应,否则将无济于事。

感谢John的帮助。我已经用您和我的代码中的代码片段更新了我的问题。但是我在catch块中遇到错误,要求我删除异常。但是我想你告诉过我,
ThreadTask
需要对
中断做出响应。对吗?我知道,我可以添加
Thread.sleep
,但在实际代码中,我将对数据库执行
selectsql调用。你知道我怎么做吗?或者,如果您可以通过组合您的代码和我的代码来为我提供完整的流程,这对我也会有很大帮助。还有一件事,
newScheduledThreadPool(n)
这里n应该与
newFixedThreadPool(noOfThreads)的线程数相同对吗?嗨,约翰,你能帮我回答我的问题吗?提前感谢。
还有一件事,newScheduledThreadPool(n)
不一定。您可以使用1个或几个线程。它们所要做的就是向其他线程发出信号,它们应该取消。该线程通常不会做太多工作。
您知道如何做吗?
取决于SQL驱动程序本身