【问题标题】:How can I get the number (ID) of a Thread in a FixedPool?如何获取 FixedPool 中线程的编号 (ID)?
【发布时间】:2018-04-29 13:52:22
【问题描述】:

我知道 Thread.currentThread().getName() 给了我池名称和池中这个线程的 ID,我怎样才能得到这个数字?

这是我提到的那一行的结果:

pool-1-thread-1

我只需要最后一个数字。

【问题讨论】:

  • 问题是,在我的代码中,我有多个线程在运行,所以 id 不是池中的那些,当我想要 1,2 和 3 时,我得到像 38,39,40 这样的值.
  • @J.FF 听起来你不想要线程 ID 本身,而是一个仅限于这个线程池的序列号。对吗?
  • XY Problem 也许?

标签: java multithreading threadpool


【解决方案1】:

对于一般情况没有用,但可以为我完成工作:

Thread.currentThread().getName().substring(Thread.currentThread().getName().length()-1)

【讨论】:

  • 这只会在ids 只有一位数字时起作用。
  • 是的,我知道这一点,但由于我使用的是带有 3 个线程的 FixedThredPool,所以这并不是真正的问题。我知道解决方案不是最好的,但我只需要在 GUI 中显示这些 ID。
【解决方案2】:

当您通过Executors.newFixedThreadPool 创建ThreadPoolExecutor 时,它将创建一个默认的ThreadFactory,而这个默认的ThreadFactory 会创建一个名称类似于pool-x-thread-yThread

您可以自定义一个ThreadFactory 并使用它来构建线程池:

class NumberThreadFactory implements ThreadFactory {        
    int count = 0;
    public Thread newThread(Runnable r) {
        return new Thread(r, String.valueOf(count++));
    }
}

Executor executor = Executors.newFixedThreadPool(2, new NumberThreadFactory());

executor.execute(() -> System.out.println(Thread.currentThread().getName()));  // 1
executor.execute(() -> System.out.println(Thread.currentThread().getName()));  // 2

【讨论】:

    猜你喜欢
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2012-01-28
    • 2010-12-13
    • 1970-01-01
    相关资源
    最近更新 更多