固定线程池立即退出,不处理线程

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


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

    }

}


慕姐8265434
浏览 161回答 1
1回答

达令说

exec.shutdown()不阻塞主线程。如果您需要等待所有提交的任务完成,您需要exec.awaitTermination(1, TimeUnit.HOUR);在调用exec.shutdown();./**&nbsp;* Blocks until all tasks have completed execution after a shutdown&nbsp;* request, or the timeout occurs, or the current thread is&nbsp;* interrupted, whichever happens first.&nbsp;*/boolean awaitTermination(long timeout, TimeUnit unit)&nbsp; &nbsp; throws InterruptedException;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java