自定义线程工厂
来源:互联网 发布:虚拟机 mac osx 编辑:程序博客网 时间:2024/06/04 01:34
JDK线程 池:Executors.newFixedThreadPool , Executors.newSingleThreadExecutor,由一个 ThreadFactory来创建新的线程,默认情况下为 Executors.defaultThreadFactory(),ThreadFactory接口
public interface ThreadFactory { Thread newThread(Runnable r);}我们可以采用自定义的ThreadFactory工厂。它创建一个新的MyAppThread实例,并将一个特定于线程池的名字传递给MyAppThread的构造函数,从而可以在线程转储和错误日志信息中区分来自不同线程池的线程。在应用程序的其他地方也可以使用MyAppThread,一边所有的线程都能使用它的调试功能
import java.util.concurrent.*;public class MyThreadFactory implements ThreadFactory { private final String poolName; public MyThreadFactory(String poolName) { this.poolName = poolName; } public Thread newThread(Runnable runnable) { return new MyAppThread(runnable, poolName); }}
在MyAppThread中还可以定制其他行为,如下面程序中,包括:为线程指定名字,设置自定义UncaughtExceptionHandler向Logger中写入信息,维护一些统计信息(包括有多少个线程被创建和销毁),以及在线程被创建或者终止时把调试消息写入日志
import java.util.concurrent.atomic.*;import java.util.logging.*;public class MyAppThread extends Thread { public static final String DEFAULT_NAME = "MyAppThread"; private static volatile boolean debugLifecycle = false; private static final AtomicInteger created = new AtomicInteger(); private static final AtomicInteger alive = new AtomicInteger(); private static final Logger log = Logger.getAnonymousLogger(); public MyAppThread(Runnable r) { this(r, DEFAULT_NAME); } public MyAppThread(Runnable runnable, String name) { super(runnable, name + "-" + created.incrementAndGet()); setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { log.log(Level.SEVERE, "UNCAUGHT in thread " + t.getName(), e); } }); } public void run() { //复制debug标志以确保一致的值 boolean debug = debugLifecycle; if (debug) log.log(Level.FINE, "Created " + getName()); try { alive.incrementAndGet(); super.run(); } finally { alive.decrementAndGet(); if (debug) log.log(Level.FINE, "Exiting " + getName()); } } public static int getThreadsCreated() { return created.get(); } public static int getThreadsAlive() { return alive.get(); } public static boolean getDebug() { return debugLifecycle; } public static void setDebug(boolean b) { debugLifecycle = b; }}
下面是main方法调用
public static void main(String args[]){ ExecutorService es = Executors.newFixedThreadPool(5, new MyThreadFactory("threadName")); }
- 自定义线程工厂
- java.util.concurrent解读,自定义线程工厂,线程池
- 线程工厂
- 线程工厂
- 简单的线程工厂
- 线程工厂源代码
- 线程工厂 ThreadFactory
- java线程工厂
- MyBatis-创建自定义工厂
- 自定义线程
- 自定义线程
- 线程工厂 ThreadFactory源码解读
- 线程工厂 ThreadFactory源码解读
- Java使用线程池和线程工厂
- 工厂(方法)模式->自定义版本
- 自定义视图与工厂模式
- 自定义线程池(1)
- 自定义线程池(2)
- java和c++互调原则
- POJ 2503 Babelfish
- OLE/COM 对象查看器——查看已注册控件的属性和方法(自己整理)
- C++中的多态
- 改过来了 输出素数。。。。。
- 自定义线程工厂
- Linux虚拟文件系统之文件打开(sys_open())
- 转载---js 数组Array用法
- 两块硬盘,安装window7和ubuntu双系统
- 如何在Cisco交换机上配置语音VLAN
- 博客园
- Web工程师必备的在线工具箱
- 求10000内的回文数
- Linux下用户编程接口API表