本文主要是介绍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-";}/*** 创建线程*/@Overridepublic 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 {@Overridepublic 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();}}
这篇关于JAVA ThreadPool ThreadFactory的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!