shutdown和awaitTermination

public class Task implements Callable {

    @Override
    public Object call() throws Exception {
        System.out.println("普通任务");
        return null;
    }
}

public class LongTask implements Callable {
    @Override
    public Object call() throws Exception {
        System.out.println("长时间任务");
        TimeUnit.SECONDS.sleep(5);
        return null;
    }
}
public class TestMain {
    public static void main(String[] args) throws InterruptedException {

        ScheduledExecutorService service = Executors.newScheduledThreadPool(4);
        service.submit(new Task());
        service.submit(new Task());
        service.submit(new LongTask());
        service.submit(new Task());
        service.shutdown();   //他不会接收新的提交任务, 他会等待已经提交未执行或正在执行的任务执行完毕后, 关闭线程池

        while(!service.awaitTermination(1,TimeUnit.SECONDS)){
            System.out.println("线程池没有关闭");
        }

        System.out.println("线程池已经关闭啦");

    }
}

猜你喜欢

转载自blog.csdn.net/mxj588love/article/details/80060429