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