Tap*_*ose 3 java lifecycle multithreading
可以在创建线程时记录.我们需要一个自定义ThreadFactory实现,从中创建所有线程,并从newThread我们可以记录的方法.但是如果我们需要记录线程被销毁和删除的时候我们怎么做呢?
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
public enum MyThreadFactory implements ThreadFactory {
INSTANCE;
private final AtomicInteger poolNumber = new AtomicInteger(1);
private final Logger logger = Logger.getLogger(getClass());
private final ThreadGroup threadGroup;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
private RpiThreadFactory() {
SecurityManager securityManager = System.getSecurityManager();
threadGroup = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
namePrefix = "RpiPool-" + poolNumber.getAndIncrement() + "-Thread-";
}
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(threadGroup, runnable, namePrefix + threadNumber.getAndIncrement(), 0);
thread.setPriority(Thread.NORM_PRIORITY);
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable cause) {
logger.error(cause.getMessage(), cause);
}
});
logger.debug(thread.toString() + " created.");
return thread;
}
}
Run Code Online (Sandbox Code Playgroud)
由于您已经在实现自己的线程工厂,因此一种方法是将runnable包装到另一个可在作业启动和完成时记录的runnable中.像这样:
public Thread newThread(Runnable runnable) {
Runnable wrapper = new Runnable() {
@Override
public void run() {
System.out.println("Starting thread ...");
try {
runnable.run();
System.out.println("Thread done");
} catch (Throwable t) {
System.out.println("Thread exited abnormally");
// Log exception
}
}
};
Thread thread = new Thread(threadGroup, wrapper, namePrefix + threadNumber.getAndIncrement(), 0);
// ...
}
Run Code Online (Sandbox Code Playgroud)
这不记录实际的线程生命周期,但与例如信任终结器在线程被销毁时进行记录相比,它是可靠的.
替换System.out.println为您选择的日志记录调用.
| 归档时间: |
|
| 查看次数: |
722 次 |
| 最近记录: |