package com.yt.distribution.pub.util;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 线程池的基类
* @author tyg
* @date 2017年12月19日下午2:56:09
*/
public class ThreadUtils {
//线程池
static ThreadPoolExecutor t = null;
//线程池中的线程数
static final int CORE_POOL_SIZE = 10;
//最大线程数
static final int POOL_MAX_SIZE = 200000;
//存在的时间,当线程池中的线程数大于corePoolSize时,如果一个线程空闲的时间达到keepAliveTime,
//则会终止,直到线程池中的线程数不超过corePoolSize。但是如果调用了allowCoreThreadTimeOut(boolean)方法,
//在线程池中的线程数不大于corePoolSize时,keepAliveTime参数也会起作用,直到线程池中的线程数为0
static final long KEEP_ALIVE_TIME = 3L;
//存在的时间单位
static final TimeUnit UNIT = TimeUnit.SECONDS;
//默认基于链表的方式,每次执行5个
static LinkedBlockingQueue<Runnable> linkQueue = new LinkedBlockingQueue<Runnable>(5);
static {
t = new ThreadPoolExecutor(CORE_POOL_SIZE, POOL_MAX_SIZE, KEEP_ALIVE_TIME, UNIT, linkQueue);
}
/**
* submit执行线程,有返回值
* @param run
* @return
* @return Future<?>
* @author tyg
* @date 2017年12月19日下午3:17:50
*/
public static Future<?> submit(Runnable run){
Future<?> submit = t.submit(run);
return submit;
}
/**
* execute执行线程
* @param run
* @return
* @return Future<?>
* @author tyg
* @date 2017年12月19日下午3:17:50
*/
public static void execute(Runnable run){
t.execute(run);
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
for(int i = 0; i < 50; i++){
t.submit(new Runnable(){
@Override
public void run() {
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("线程池中线程数目:"+t.getPoolSize()+",队列中等待执行的任务数目:"+
t.getQueue().size()+",已执行完别的任务数目:"+t.getCompletedTaskCount());
}
});
}
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("创建成功之后看是否销毁线程池中新建的线程,剩余数目:"+t.getPoolSize());
}
}