java如何更改线程名称
java如何更改线程名称
这篇文章主要介绍了java如何更改线程名称,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
更改线程名称
为了简化日志读取和线程转储,可以自定义线程的名称。这可以通过创建ExecutorService时用一个ThreadFactory来完成。在流行的实用程序库中有许多ThreadFactory接口的实现:
com.google.common.util.concurrent.ThreadFactoryBuilde+rinGuava.org.springframework.scheduling.concurrent.CustomizableThreadFactoryinSpring.org.apache.commons.lang3.concurrent.BasicThreadFactoryinApacheCommonsLang3.
ThreadFactorythreadFactory=newBasicThreadFactory.Builder().namingPattern("computation-thread-%d").build();ExecutorServiceexecutorService=Executors.newFixedThreadPool(numberOfThreads,threadFactory);
尽管ForkJoinPool不使用ThreadFactory接口,但也支持对线程的重命名:
ForkJoinPool.ForkJoinWorkerThreadFactoryforkJoinThreadFactory=pool->{ForkJoinWorkerThreadthread=ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);thread.setName("computation-thread-"+thread.getPoolIndex());returnthread;};ForkJoinPoolforkJoinPool=newForkJoinPool(numberOfThreads,forkJoinThreadFactory,null,false);
将线程转储与默认命名进行比较:
"pool-1-thread-3"#14prio=5os_prio=31tid=0x00007fc06b19f000nid=0x5703runnable[0x0000700001ff9000]java.lang.Thread.State:RUNNABLEatcom.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.TaskHandler.compute(TaskHandler.java:16)..."pool-2-thread-3"#15prio=5os_prio=31tid=0x00007fc06aa10800nid=0x5903runnable[0x00007000020fc000]java.lang.Thread.State:RUNNABLEatcom.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.HealthCheckCallback.recordFailure(HealthChecker.java:21)atcom.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.HealthChecker.check(HealthChecker.java:9)..."pool-1-thread-2"#12prio=5os_prio=31tid=0x00007fc06aa10000nid=0x5303runnable[0x0000700001df3000]java.lang.Thread.State:RUNNABLEatcom.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.TaskHandler.compute(TaskHandler.java:16)...
与自定义命名进行比较:
"task-handler-thread-1"#14prio=5os_prio=31tid=0x00007fb49c9df000nid=0x5703runnable[0x000070000334a000]java.lang.Thread.State:RUNNABLEatcom.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.TaskHandler.compute(TaskHandler.java:16)..."authentication-service-ping-thread-0"#15prio=5os_prio=31tid=0x00007fb49c9de000nid=0x5903runnable[0x0000700003247000]java.lang.Thread.State:RUNNABLEatcom.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.HealthCheckCallback.recordFailure(HealthChecker.java:21)atcom.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.HealthChecker.check(HealthChecker.java:9)..."task-handler-thread-0"#12prio=5os_prio=31tid=0x00007fb49b9b5000nid=0x5303runnable[0x0000700003144000]java.lang.Thread.State:RUNNABLEatcom.github.sorokinigor.article.tipsaboutconcurrency.setthreadsname.TaskHandler.compute(TaskHandler.java:16)...
想象一下,可能会不止3个线程。
感谢你能够认真阅读完这篇文章,希望小编分享的“java如何更改线程名称”这篇文章对大家有帮助,同时也希望大家多多支持恰卡编程网,关注恰卡编程网行业资讯频道,更多相关知识等着你来学习!