import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.logging.*;
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);
}
public static void main(String[] args) {
ExecutorService tpe = new ThreadPoolExecutor(5, 5,
10, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10),
new MyThreadFactory("my fix-sized thread pool factory"),
new ThreadPoolExecutor.CallerRunsPolicy());
tpe.submit(() -> System.out.println("a"));
tpe.submit(() -> System.out.println("b"));
tpe.submit(() -> System.out.println("c"));
tpe.submit(() -> System.out.println("d"));
tpe.shutdown();
}
}
class MyAppThread extends Thread {
public static final String DEFAULT_NAME = "MyAppThread";
private static volatile boolean debugLifecycle = true;
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);
final ConsoleHandler consoleHandler = new ConsoleHandler();
log.addHandler(consoleHandler);
}
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() {
// Copy debug flag to ensure consistent value throughout.
boolean debug = debugLifecycle;
if (debug)
log.log(Level.INFO, "Created " + getName());
try {
alive.incrementAndGet();
super.run();
} finally {
alive.decrementAndGet();
if (debug) log.log(Level.INFO, "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;
}
}
In the above example, MyThreadFactory override the newThread method and return a customized thread object. The MyAppThread added logging and statistics to the thread creation process.