基本原理:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExecutorsDemo { // 创建线程池的两种方法 // 1、Executors.newCachedThreadPool(); // 2、Executors.newFixedThreadPool(10); 指定线程池最大值 public static void main(String[] args) { method1(); method2(); } private static void method2() { // 参数不是初始值,是最大值 ExecutorService es = Executors.newFixedThreadPool(10); es.submit(() -> { System.out.println(Thread.currentThread().getName() + "执行了"); }); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } es.submit(() -> { System.out.println(Thread.currentThread().getName() + "执行了"); }); // 关闭线程池 es.shutdown(); } private static void method1() { // Executors创建一个线程池 // ExecutorService控制线程池 // 创建一个线程池,池子默认是空的,默认最多可容纳int的最大值 ExecutorService es = Executors.newCachedThreadPool(); es.submit(() -> { System.out.println(Thread.currentThread().getName() + "执行了"); }); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } es.submit(() -> { System.out.println(Thread.currentThread().getName() + "执行了"); }); // 关闭线程池 es.shutdown(); } }
标签:Thread,currentThread,Executors,System,线程,es From: https://www.cnblogs.com/weiduaini/p/17213029.html