0

我正在尝试制作一个ExecutorService可以为每个线程提供超时或中断的实现。

在我下面的例子中,假设我正在产卵2 threads(在实际场景中,这个数字会很高),那么我需要确保each thread应该运行10 minutes. 这意味着,Thread1 will run for 10 minutesThread2 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) {

            }
        }
    }
}
4

2 回答 2

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需要响应中断,否则这将无济于事。

于 2013-02-25T02:55:11.527 回答
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 进程那样“杀死”线程。

于 2013-02-25T02:47:32.167 回答