Java:尽管执行非常简单的任务,线程仍需要很长时间才能完成

我目前有一个使用Threadpool并生成Runnable线程的Java程序。由于某些原因,尽管线程没有执行任何复杂的逻辑,但它们仍需要很长时间才能完成。

这是我的线程类...

public class MyThread implements Runnable {

    public MyThread(){}

    @Override
    public void run(){
        System.out.println("Hello");
    }

}

这是我产生线程的地方...

public void testThreads(){

    ExecutorService threadPool = Executors.newFixedThreadPool(5);
    List<Future<?>> tasks = new LinkedList<>();

    for(int i = 0; i < 10; i++){

        tasks.add(threadPool.submit(new MyThread());

    }

    // Waiting for threads to complete
    for (Future<?> currTask : tasks) {
        try {
            currTask.get();
        } catch (Throwable thrown) {
            context.getLogger().log("Error while waiting for thread completion");
        }
    }

}

由于某种原因,在For循环中,当我等待所有线程完成时,大约需要10秒钟以上的时间。为什么是这样?为什么线程需要这么长时间才能完成?

wang532948001 回答:Java:尽管执行非常简单的任务,线程仍需要很长时间才能完成

由于某些线程永不终止,该程序挂起。为了正确终止程序,所有非守护程序线程应先终止 (请参见Thread类的Javadoc)。

执行程序服务将启动自己的(非守护程序)工作线程,在执行所有任务后,这些线程将保持运行状态(处于等待状态)。

为了确保程序终止,请调用executorService.shutdown()停止其工作线程。

public void testThreads() {
  ExecutorService threadPool = Executors.newFixedThreadPool(4);
  List<Future<?>> tasks = new LinkedList<>();
  for (int i = 0; i < 10; i++) {
    tasks.add(threadPool.submit(new MyThread()));
  }
  /*
   * no need to wait on each future- just call shutdown(),* the executor will run all pending tasks
   * and will then stop its worker threads
   */
  threadPool.shutdown();
}
本文链接:https://www.f2er.com/3131630.html

大家都在问