java线程池创建及核心线程池过期设置

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 
 */

/**
 *
 * @author 曾谢波
 * @since 2018年7月25日
 */
public class TemporaryTest {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		Callable<String> callable = new Callable<String>() {
			@Override
			public String call() throws Exception {
				TimeUnit.SECONDS.sleep(4);
				return "测试callable";
			}
		};
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				try {
					TimeUnit.SECONDS.sleep(4);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("测试Runnable");

			}
		};

		/*
		 * 创建一个线程池
		 *
		 * @param corePoolSize 核心线程数
		 * 
		 * @param maximumPoolSize 当workQueue存放满时创建线程所能达到的最大线程数
		 * 
		 * @param keepAliveTime 除核心线程外的线程空闲超过此时间就会被回收,设置为零意味着空闲线程立即终止
		 * 
		 * @param unit keepAliveTime时间单位
		 * 
		 * @param workQueue 超过核心线程数的线程存放地址即待执行线程,一般会设置一个大小,防止内存溢出
		 * 
		 * @param threadFactory 当executor创建线程时使用的线程工厂
		 * 
		 * @param handler 当执行被阻塞时采用的处理策略
		 */
		ThreadPoolExecutor executorService = new ThreadPoolExecutor(5, 10, 10, TimeUnit.SECONDS,
				new LinkedBlockingQueue<>(10), new MyDefaultThreadFactory("TestThreadPool", false, 0),
				new ThreadPoolExecutor.AbortPolicy());
		// 设置使核心线程空闲时间超过keepAliveTime时间也被回收,这样线程池没有任务执行最终会自动销毁
		executorService.allowCoreThreadTimeOut(true);
		Future<String> future = executorService.submit(callable);
		System.out.println(future.get());
		System.out.println("---------------------------");
		String result = "测试submit(runnable, result)";
		Future<String> future2 = executorService.submit(runnable, result);
		System.out.println(future2.get());
		System.out.println("==========end===========");
		
		
	}

}

/**
 * 搬的Executors中的DefaultThreadFactory类,修改一下作为线程工厂
 */
class MyDefaultThreadFactory implements ThreadFactory {
	private static final AtomicInteger poolNumber = new AtomicInteger(1);
	private final ThreadGroup group;
	private final AtomicInteger threadNumber = new AtomicInteger(1);
	private final String namePrefix;
	private final boolean isDaemon;
	private final long stackSize;

	/**
	 * @param poolName
	 *            自定义的线程池名称
	 * @param isDaemon
	 *            是否是守护线程
	 * @param stackSize
	 *            新线程所需的堆栈大小,或者为零以指示要忽略此参数
	 */
	MyDefaultThreadFactory(String poolName, boolean isDaemon, long stackSize) {
		SecurityManager s = System.getSecurityManager();
		group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
		namePrefix = "pool-" + poolName + poolNumber.getAndIncrement() + "-thread-";
		this.isDaemon = isDaemon;
		this.stackSize = stackSize;

	}

	public Thread newThread(Runnable r) {
		Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), stackSize);
		t.setDaemon(isDaemon);
		if (t.getPriority() != Thread.NORM_PRIORITY)
			t.setPriority(Thread.NORM_PRIORITY);
		return t;
	}
}

执行结果:

测试callable
---------------------------
测试Runnable
测试submit(runnable, result)
==========end===========

猜你喜欢

转载自blog.csdn.net/ncuzengxiebo/article/details/81209677