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