如何在特定的非线程类中打印出当前运行的线程名称?

9
我发现了如何在类Thread或继承Thread的子类中打印特定线程名称的答案。
例如:this.getName(); 然而,当我在我的类QueueManager<T>中时,这对我不起作用。例如,在我的方法removeFromQueue()中,我想打印正在从队列中取出的线程。但是当我使用this时,它指的是类QueueManager<T>而不是当前线程。
如何从该类内部引用当前线程?
public T removeFromQueue(){
        synchronized (this) {
            T item = null;

            if (!isEmpty()){
                item = queue.removeLast();
                if (WebServer.DEBUG) System.out.println(item + " removed from " + item.getClass() + "Queue" + "\nby " + this.);
                //If queue was full until right now, notify waiting socket threads that they can add something 
                if (getSize() == (maxQueueSize - 1)){
                    notifyAll();
                }
            }
            return item; //If queue is empty, null is returned.
        }
    }
1个回答

20

当前线程的名称始终由

Thread.currentThread().getName()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接