java线程池

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());
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值