Java高并发之线程池详解(3)

class NamedThreadFactory implements ThreadFactory {
    private static final AtomicInteger threadIndex = new AtomicInteger(0);
    private final String baseName;
    private final boolean daemon;

public NamedThreadFactory(String baseName) {
        this(baseName, true);
    }

public NamedThreadFactory(String baseName, boolean daemon) {
        this.baseName = baseName;
        this.daemon = daemon;
    }

public Thread newThread(Runnable runnable) {
        Thread thread = new Thread(runnable, this.baseName + "-" + threadIndex.getAndIncrement());
        thread.setDaemon(this.daemon);
        return thread;
    }
}

关闭线程池

跟直接new Thread不一样, 局部变量的线程池, 需要手动关闭, 不然会导致线程泄漏问题.

默认提供两种方式关闭线程池.

shutdown: 等所有任务, 包括阻塞队列中的执行完, 才会终止, 但是不会接受新任务.

shutdownNow: 立即终止线程池, 打断正在执行的任务, 清空队列. 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/c672bb3ceae89238c5b266979a88a7f8.html