gpt4 book ai didi

java - Java ThreadFactory 的问题

转载 作者:搜寻专家 更新时间:2023-11-01 02:18:38 27 4
gpt4 key购买 nike

在我的应用程序中,我使用带有自定义 ThreadFactory 的线程池。

我的代码如下:

pool = Executors.newScheduledThreadPool(10, new TF());

class TF implements ThreadFactory {
AtomicInteger count = new AtomicInteger(1);
public synchronized Thread newThread(Runnable r) {
Thread t = new Thread(r) ;
t.setName("ThreadPool Thread[" + count.getAndIncrement() + "]");
t.setUncaughtExceptionHandler(new UEHLogger());
return t;
}
}

但是,在将各种 Runnable 提交到线程池之后,如果我转储当前线程(来自 IDE,Intellij IDEA),我得到:

"ThreadPool Thread[1]" daemon prio=6 tid=0x0334e000 nid=0x1130 waiting on condition [0x0377f000..0x0377fc94]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x22fa7838> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1925)
at java.util.concurrent.DelayQueue.take(DelayQueue.java:160)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:583)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:576)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)

"ThreadPool Thread[1]" daemon prio=6 tid=0x0333e400 nid=0x128 waiting on condition [0x0372f000..0x0372fd14]
java.lang.Thread.State: TIMED_WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x22edb9e0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:198)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:1963)
at java.util.concurrent.DelayQueue.take(DelayQueue.java:164)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:583)
at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:576)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)

(以及线程 2-9 的类似堆栈跟踪)

所以基本上不是获取线程编号 1,2,3,4,5,6,7,8,9,10,而是获取线程编号 1,1,2,3,4,5,6,7,8 ,9

一切似乎都正常,但显然令人不安。

最佳答案

您不会无意中创建了两个线程池(或两个 ThreadFactories),对吗?

通过让每个线程输出其线程工厂的 ID 及其自己的 ID 来确认这一点可能是一个想法。

关于java - Java ThreadFactory 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/797295/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com