ExecutorService 固定池线程挂起

Jav*_*a P 5 java concurrency multithreading

我在我们的代码中使用以下代码片段。

ExecutorService executor = Executors.newFixedThreadPool(4);
while(loop 50 times){
    //In the extreme case I will have 50 threads and only 4 will be active and remaining are in queue 
    MyThread myThread = new MyThread();
    executor.execute(myThread);//Each Thread process 100,000 records and put in a file
}
executor.shutdown();
while (!executor.isTerminated()) {
}
Run Code Online (Sandbox Code Playgroud)

以下是我的问题:

  1. 它挂在第二个 while 循环中。可能是什么原因?
  2. 有没有办法在一定间隔后终止整个线程池?
  3. 我可以在一定时间间隔后终止线程吗?

请帮我解决这个问题。

Man*_*and 4

1.它挂在第二个while循环上。可能是什么原因?

挂起的原因可能是因为与需要处理和存储在文件中的记录量相比,线程很少。如果每个线程要处理 100,000 条记录并放入文件中,则由 4 个线程共享的 50 个线程任务将必须处理 50 个文件中的 5,000,000 条记录。所以最好增加线程数并检查。还要记下每个线程所花费的时间,以有效衡量是否通过增加固定池线程的数量来减少总体所花费的时间。

2.有没有办法在一定时间间隔后终止整个线程池?

是的,下面的代码表明:-

executor.shutdown();
executor.awaitTermination(60, TimeUnit.SECONDS); // blocks/waits for certain interval as specified
executor.shutdownNow(); // Forcefully terminate entire thread pool after the above time.
Run Code Online (Sandbox Code Playgroud)

3.我可以在一定时间间隔后终止线程吗?

是的,如果终止线程的原因实际上是停止它正在执行的任务。为了实现这一点,我们需要获取对 future 的引用,并有条件地等待一段时间,然后再强制取消任务并中断执行任务的线程。

        Map<String, Future> tasks = new HashMap<String, Future>();
        while(i++ < 50){
            //In the extreme case I will have 50 threads and only 4 will be active and remaining are in queue 
            Thread myThread = new Thread();
            tasks.put("Thread"+i ,executor.submit(myThread));//Each Thread process 100,000 records and put in a file
        }
        // say you want to terminate Thread2 after 60 seconds
        Future thread2Task = tasks.get("Thread2");
        thread2Task.get(60, TimeUnit.SECONDS);
        thread2Task.cancel(true); // boolean whether you want to interrupt the thred forcefully
Run Code Online (Sandbox Code Playgroud)