【问题标题】:Fixed Thread Pool is exiting immediately, not processing threads固定线程池立即退出,不处理线程
【发布时间】:2018-10-03 17:48:26
【问题描述】:

为了理解固定线程池,我编写了这个测试代码,它显示了以下结果,与我认为的相反:

Thread Start: 1
Thread Start: 2
Thread Start: 0

就是这样。没有“线程结束”消息,只启动了 3 个线程。

我期望并且我希望完成所有 10 项任务。

ExecutorService exec = Executors.newFixedThreadPool(3);

for (int c = 0; c < 10; c++) {
    exec.execute(new TestThread(c));
}
exec.shutdown();

public class TestThread implements Runnable {

    private int counter;

    public TestThread (int counter) {
        this.counter = counter;
    }

    @Override
    public void run() {
        System.out.println("Thread Start: " + counter);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Thread End: " + counter);
    }
}

【问题讨论】:

  • 效果很好。但你必须在完成与 exec 的工作后调用 exec.shutdown()。
  • @Amin shutdown 将“锁定”执行程序并开始杀死空闲线程。不需要为了“让它工作”而调用它
  • 你的意思是它运作良好?它打印我展示的内容。其他 7 个线程在哪里,为什么不打印“线程结束”
  • @Moonstone 不是 其他 7 个线程,因为您只有 3 个线程,而是“其他任务*
  • 因为我检查它并且工作。关于关机,我知道如果你没有调用它,它就是等待接受更多可运行和可调用并且程序没有完成。

标签: java multithreading java-threads


【解决方案1】:

exec.shutdown() 不会阻塞主线程。如果您需要等待所有提交的任务完成,您需要在调用exec.shutdown(); 后调用exec.awaitTermination(1, TimeUnit.HOUR);(当然超时对您的应用程序来说是有意义的)。

/**
 * Blocks until all tasks have completed execution after a shutdown
 * request, or the timeout occurs, or the current thread is
 * interrupted, whichever happens first.
 */
boolean awaitTermination(long timeout, TimeUnit unit)
    throws InterruptedException;

【讨论】:

  • 那是我的问题,在更大的应用程序的上下文中,system.exit() 被调用,我错误地认为程序会等待线程队列。
猜你喜欢
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-08
  • 1970-01-01
  • 2015-02-28
  • 2011-11-03
相关资源
最近更新 更多