线程池简单使用 先看一段代码 package ThreadTest ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; public class PoolDemo { public static void main ( String [] args ) { //单一线程
线程池简单使用
先看一段代码
package ThreadTest;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PoolDemo {
public static void main(String[] args) {
//单一线程的线程池
//ExecutorService executorService = Executors.newSingleThreadExecutor();
//固定个数线程的线程池
//ExecutorService executorService = Executors.newFixedThreadPool(5);
//可变长度的线程池
ExecutorService executorService = Executors.newCachedThreadPool();
try {
for (int i = 1; i <= 100; i++) {
int finalI = i;
executorService.execute(()->{
System.out.println(Thread.currentThread().getName() + " " + finalI);
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
线程池的七个参数
将上面线程池的源码找出来:
newSIngleThreadExecutor
newFixedThreadPool
newCachedThreadPool
三个线程池的核心都是下面这个函数
参数分析:
int maximumPoolSize,//最大线程池大小
long keepAliveTime,//超时了没有人调用就会释放(非核心区)
TimeUnit unit,//超时时间单位
BlockingQueue<Runnable> workQueue,//阻塞队列
ThreadFactory threadFactory, //创建线程的工厂
RejectedExecutionHandler handler //拒绝策略
)
{
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈