// 一系列判断,主要是判断是否符合给线程池创建新的线程 int c = ctl.get(); if (runStateLessThan(c, STOP)) { if (!completedAbruptly) { int min = allowCoreThreadTimeOut ? 0 : corePoolSize; if (min == 0 && ! workQueue.isEmpty()) min = 1; if (workerCountOf(c) >= min) return; } // 给线程池创建新的线程,core之所以传递false,是因为这里要防止创建失败 addWorker(null, false); } }
publicstaticvoidmain(String[] args){ ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 5, 10, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(30)); for (int i = 0; i < 10; i++) { int finalI = i; Thread t = new Thread(() -> { System.out.println(10 / finalI - 5); }); pool.execute(t); } }
publicstaticvoidmain(String[] args){ ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 5, 10, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(30)); for (int i = 0; i < 10; i++) { int finalI = i; Thread t = new Thread(() -> { System.out.println(10 / finalI - 5);
忽的一下,想到了线程池的比较重要的一个参数:ThreadFactory接口,这个接口的作用是按需创建新线程的,使用线程工厂消除了对Thread#Thread(Runnable) new Thread的强依赖,使应用程序能够使用特殊的Thread子类、优先级等。大白话就是让线程池中的线程使用我们自定义的线程,这个自定义可不是我们通过execute()或submit()传进来的自定义线程,而是Worker类中的thread变量,也就是实际运行的线程,我们看一下Worker类的构造方法
public Thread newThread(Runnable r){ Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; }
publicstaticvoidmain(String[] args){ ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 5, 10, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(30), r -> { Thread t = new Thread(r); t.setUncaughtExceptionHandler((t1, e) -> System.out.println("发生了异常")); return t; }); for (int i = 0; i < 10; i++) { int finalI = i; Thread t = new Thread(() -> { System.out.println(10 / finalI - 5);