Executors创建线程池的几种方式以及使用
Java通过Executors提供四种线程池,分别为:
1.newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
2.newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
3.newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
4.newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
直接上代码:
1 import lombok.experimental.Delegate; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 6 public class ThreadUtil { 7 8 //维护一个单例线程 9 private static final ThreadUtil threadUtil = new ThreadUtil(); 10 11 // 代理模式 这样可以直接调用父类中的方法 12 // public interface ExecutorService extends Executor 13 //public interface Executor { 14 15 /** 16 * Executes the given command at some time in the future. The command 17 * may execute in a new thread, in a pooled thread, or in the calling 18 * thread, at the discretion of the {@code Executor} implementation. 19 * 20 * @param command the runnable task 21 * @throws RejectedExecutionException if this task cannot be 22 * accepted for execution 23 * @throws NullPointerException if command is null 24 */ 25 void execute(Runnable command); 26 } 27 28 // 1.采用newCachedThreadPool创建线程池 29 @Delegate 30 public ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); 31 32 //2.采用newFixedThreadPool创建线程池 33 @Delegate 34 public ExecutorService service = Executors.newFixedThreadPool(3); 35 36 //3.采用newScheduledThreadPool 创建一个定长线程池 支持定时及周期性任务执行。 37 // 使用方法: ThreadUtil.getInstance().schedule(new TestThread(),3, TimeUnit.SECONDS); 38 @Delegate 39 public ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(2); 40 41 42 //4.采用newSingleThreadExecutor 创建一个单线程化的线程池 43 @Delegate 44 public ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor(); 45 46 public static ThreadUtil getInstance() { 47 return threadUtil; 48 } 49 50 }
1 @Override 2 public String sendMsg() throws Exception { 3 4 //把业务内容放在类中 5 ThreadUtil.getInstance().execute(new TestThread()); 6 7 //或者这样直接写业务内容 8 ThreadUtil.getInstance().execute( () -> { 9 10 System.out.println("222"); 11 12 // 打印线程的内存地址 13 System.out.println(System.identityHashCode(Thread.currentThread())); 14 15 System.out.println(Thread.currentThread().getName()); 16 } 17 ); 18 return "ok"; 19 } 20 21 private class TestThread implements Runnable{ 22 23 @Override 24 public void run() { 25 System.out.println("111"); 26 27 System.out.println(Thread.currentThread().getName()); 28 29 System.out.println(System.identityHashCode(Thread.currentThread())); 30 } 31 }
hello world!!!