java-为什么缓存的线程池会创建两个线程,为什么关闭它会改变它呢?

这是我的Java代码.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

class ExceptionThread2 implements Runnable {
    @Override
    public void run() {
        Thread t = Thread.currentThread();
        System.out.println("run() by " + t);
        System.out.println("eh = " + t.getUncaughtExceptionHandler());
        throw new RuntimeException();
    }
}

class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("caught " + e);
    }
}

class HandlerThreadFactory implements ThreadFactory {
    @Override
    public Thread newThread(Runnable r) {
        System.out.println(this + " creating new Thread ");
        Thread t = new Thread(r);
        System.out.println("created " + t);
        t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        System.out.println("eh = " + t.getUncaughtExceptionHandler());
        return t;
    }
}

public class CaptureUncaughtException {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
        exec.execute(new ExceptionThread2());
        //exec.shutdown();
    }
}

结果:

com.concurrent.example.HandlerThreadFactory@7f31245a creating new Thread
created Thread[Thread-0,5,main]
eh = com.concurrent.example.MyUncaughtExceptionHandler@6d6f6e28
run() by Thread[Thread-0,5,main]
eh = com.concurrent.example.MyUncaughtExceptionHandler@6d6f6e28
com.concurrent.example.HandlerThreadFactory@7f31245a creating new Thread
created Thread[Thread-1,5,main]
eh = com.concurrent.example.MyUncaughtExceptionHandler@2870fdbb
caught java.lang.RuntimeException

当我取消注释//exec.shutdown()时,结果将有所不同.仅创建一个线程.

com.concurrent.example.HandlerThreadFactory@7f31245a creating new Thread
created Thread[Thread-0,5,main]
eh = com.concurrent.example.MyUncaughtExceptionHandler@6d6f6e28
run() by Thread[Thread-0,5,main]
eh = com.concurrent.example.MyUncaughtExceptionHandler@6d6f6e28
caught java.lang.RuntimeException

为什么?

解决方法:

您的可运行崩溃其线程.因此,池将用新线程替换该线程(对于您可能提交的下一个任务).

如果池已被关闭,则不会这样做.

上一篇:java-检测当前线程是否为ExecutorService线程


下一篇:视频直播点播nginx-rtmp开发手册中文版