JAVA ThreadPool & ThreadFactory


package threadPool;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName: BasicThreadFactory
 * @Description: TODO
 * @author Zhou Shengshuai
 * @date 2014年9月22日 上午10:09:30
 * 
 */
public class BasicThreadFactory implements ThreadFactory {
	private final ThreadGroup threadGroup;
	private final AtomicInteger threadNumber = new AtomicInteger(1);
	private final String threadNamePrefix;

	/**
	 * 构造函数
	 * 
	 * @param threadPoolName
	 *            线程池名称
	 */
	public BasicThreadFactory(String threadPoolName) {
		SecurityManager securityManager = System.getSecurityManager();

		threadGroup = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();

		threadNamePrefix = threadPoolName + "-thread-";
	}

	/**
	 * 创建线程
	 */
	@Override
	public Thread newThread(Runnable runnable) {
		Thread thread = new Thread(threadGroup, runnable, threadNamePrefix + threadNumber.getAndIncrement(), 0);

		if (thread.isDaemon()) {
			thread.setDaemon(false);
		}

		if (thread.getPriority() != Thread.MAX_PRIORITY) {
			thread.setPriority(Thread.MAX_PRIORITY);
		}

		return thread;
	}
}

package threadPool;

/**
 * @ClassName: BasicThreadTask
 * @Description: TODO
 * @author Zhou Shengshuai
 * @date 2014年9月22日 上午10:12:02
 * 
 */
public class BasicThreadTask implements Runnable {

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName());
	}

}

package threadPool;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName: MainThreadTask
 * @Description: TODO
 * @author Zhou Shengshuai
 * @date 2014年9月22日 上午10:14:34
 * 
 */
public class MainThreadTask {
	private ThreadPoolExecutor threadPoolExecutor = null;

	public void initial() {
		threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new BasicThreadFactory("BasicThreadFactory"));
	}

	public void execute() {
		for (int index = 0; index < 10; index++) {
			threadPoolExecutor.execute(new BasicThreadTask());
		}
	}

	public void destroy() {
		threadPoolExecutor.shutdown();
	}

	/**
	 * @Title: main
	 * @Description: TODO
	 * @param args
	 * @throws
	 */
	public static void main(String[] args) {
		MainThreadTask mainThreadTask = new MainThreadTask();

		mainThreadTask.initial();
		mainThreadTask.execute();
		mainThreadTask.destroy();
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值