java Executor 线程池
设置线程池的属性
* 参数1:corePoolSize:核心池大小
* 参数2:maximumPoolSize:最大线程池上限个数
* 参数3:keepAliveTime:保存最长时间,任务执行完之后,要裁员的延时
* 参数4:unit:时间单位
* 参数5:workQueue:用于存储任务的工作队列(即将被执行的任务)(BlockingQueue)
* 参数6:ThreadFactory: 线程工厂, 用来创建线程的
package cn.Douzi.Thread_Pool;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadPoolTest02 {
//网络访问框架,都要用线程池
private static Executor executors = Executors.newCachedThreadPool(); //缓存线程池
private static Executor executor2 = Executors.newFixedThreadPool(5); //固定线程个数的线程
private static Executor executor3 = Executors.newScheduledThreadPool(5); //计划任务线程池
private static Executor executor4 = Executors.newSingleThreadExecutor(); //单个线程的线程池
public static void main(String[] args) {
// BlockingQueue<E> //单端队列
// BlockingDQueue //双端队列
LinkedBlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(100); //该容器的最大上限
//创建一个线程工厂
ThreadFactory threadFactlory = new ThreadFactory() {
//线程安全的int的包装类
AtomicInteger atomicInteger = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
//创建一个线程,然后把r赋值给该线程
Thread thread = new Thread(r);
thread.setName("MyThread=" + atomicInteger.getAndIncrement());
return thread;
}
};
/*
* 参数1:corePoolSize:核心池大小
* 参数2:maximumPoolSize:最大线程池上限个数
* 参数3:keepAliveTime:保存最长时间,任务执行完之后,要裁员的延时
* 参数4:unit:时间单位
* 参数5:workQueue:用于存储任务的工作队列(即将被执行的任务)(BlockingQueue)
* 参数6:ThreadFactory: 线程工厂, 用来创建线程的
*
*/
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 10, 1, TimeUnit.SECONDS, blockingQueue, threadFactlory);
/**
* 线程不是越多越好,Google工程给了一个推荐值:线程的个数=CPU核心数+1=5
*/
//用自己打造的线程池
for (int i = 0; i < 110; i++) {
poolExecutor.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
method();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
//同时最多只运行5个进程过来
public static void method() throws InterruptedException {
System.out.println("ThreadName= " + Thread.currentThread().getName()+"进来了");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ThreadName= "+Thread.currentThread().getName()+"出去了");
}
}