当前位置 : 主页 > 编程语言 > java >

线程池

来源:互联网 收集:自由互联 发布时间:2022-07-04
线程池简单使用 先看一段代码 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


线程池_阻塞队列_02


newCachedThreadPool


线程池_线程池_03
三个线程池的核心都是下面这个函数
线程池_线程池_04
参数分析:

public ThreadPoolExecutor(int corePoolSize,//核心线程池大小
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;
}

主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈

网友评论