144

タスクを送信する固定スレッドプールがあります(5スレッドに制限されています)。これらの5つのスレッドのどれが私のタスクを実行しているかをどのように見つけることができますか(「 5のスレッド#3がこのタスクを実行している」など)?

ExecutorService taskExecutor = Executors.newFixedThreadPool(5);

//in infinite loop:
taskExecutor.execute(new MyTask());
....

private class MyTask implements Runnable {
    public void run() {
        logger.debug("Thread # XXX is doing this task");//how to get thread id?
    }
}
4

6 に答える 6

250

使用Thread.currentThread()

private class MyTask implements Runnable {
    public void run() {
        long threadId = Thread.currentThread().getId();
        logger.debug("Thread # " + threadId + " is doing this task");
    }
}
于 2010-07-20T20:59:17.347 に答える
26

受け入れられた回答は、スレッドIDの取得に関する質問に答えますが、「ThreadXofY」メッセージを実行することはできません。スレッドIDはスレッド間で一意ですが、必ずしも0または1から始まるとは限りません。

質問に一致する例を次に示します。

import java.util.concurrent.*;
class ThreadIdTest {

  public static void main(String[] args) {

    final int numThreads = 5;
    ExecutorService exec = Executors.newFixedThreadPool(numThreads);

    for (int i=0; i<10; i++) {
      exec.execute(new Runnable() {
        public void run() {
          long threadId = Thread.currentThread().getId();
          System.out.println("I am thread " + threadId + " of " + numThreads);
        }
      });
    }

    exec.shutdown();
  }
}

および出力:

burhan@orion:/dev/shm$ javac ThreadIdTest.java && java ThreadIdTest
I am thread 8 of 5
I am thread 9 of 5
I am thread 10 of 5
I am thread 8 of 5
I am thread 9 of 5
I am thread 11 of 5
I am thread 8 of 5
I am thread 9 of 5
I am thread 10 of 5
I am thread 12 of 5

モジュロ演算を使用して少し調整すると、「YのスレッドX」を正しく実行できます。

// modulo gives zero-based results hence the +1
long threadId = Thread.currentThread().getId()%numThreads +1;

新しい結果:

burhan@orion:/dev/shm$ javac ThreadIdTest.java && java ThreadIdTest  
I am thread 2 of 5 
I am thread 3 of 5 
I am thread 3 of 5 
I am thread 3 of 5 
I am thread 5 of 5 
I am thread 1 of 5 
I am thread 4 of 5 
I am thread 1 of 5 
I am thread 2 of 5 
I am thread 3 of 5 
于 2013-08-20T14:09:59.347 に答える
6

Thread.getCurrentThread.getId()を使用できますが、ロガーによって管理されるLogRecordオブジェクトに既にスレッドIDがあるのに、なぜそれを実行したいのでしょうか。ログメッセージのスレッドIDをログに記録する構成がどこかにないようです。

于 2010-07-20T21:04:12.023 に答える
2

ロギングを使用している場合は、スレッド名が役立ちます。スレッドファクトリはこれを支援します:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class Main {

    static Logger LOG = LoggerFactory.getLogger(Main.class);

    static class MyTask implements Runnable {
        public void run() {
            LOG.info("A pool thread is doing this task");
        }
    }

    public static void main(String[] args) {
        ExecutorService taskExecutor = Executors.newFixedThreadPool(5, new MyThreadFactory());
        taskExecutor.execute(new MyTask());
        taskExecutor.shutdown();
    }
}

class MyThreadFactory implements ThreadFactory {
    private int counter;
    public Thread newThread(Runnable r) {
        return new Thread(r, "My thread # " + counter++);
    }
}

出力:

[   My thread # 0] Main         INFO  A pool thread is doing this task
于 2017-02-02T21:11:03.273 に答える
1

クラスがThreadを継承している場合は、メソッドgetNameを使用しsetNameて各スレッドに名前を付けることができます。nameそれ以外の場合は、フィールドをに追加MyTaskし、コンストラクターで初期化することができます。

于 2010-07-20T21:02:37.063 に答える
1

現在のスレッドを取得する方法は次のとおりです。

Thread t = Thread.currentThread();

Threadクラスオブジェクト(t)を取得すると、Threadクラスメソッドを使用して必要な情報を取得できるようになります。

スレッドIDの取得:

long tId = t.getId(); // e.g. 14291

スレッド名の取得:

String tName = t.getName(); // e.g. "pool-29-thread-7"
于 2018-07-07T14:51:40.417 に答える