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

标签 java multithreading this

我找到了关于如何在类里面打印出特定线程名称的答案 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.
        }
    }

最佳答案

当前线程的名字总是由

Thread.currentThread().getName()

关于java - 如何打印出当前在特定非线程类上运行的线程名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24377867/

相关文章:

java - HashMap 重复值 - 查找重复项的数量

java - 使用 volatile 停止线程

javascript - 构造函数第二次失败,但不是第一次

java - ClassNotFoundException : org. springframework.cache.Cache$ValueRetrievalException 异常

java - 如何将构造函数从父类(super class)继承到子类

c# - 多线程应用程序中第 4 个 HttpWebRequest 异常超时

c++ - 无法重载对 *this 的引用

javascript - 添加/删除 eventListeners,同时保持 "this"的实例上下文

java - 将 JAR 文件嵌入到 HTML 中?

c++ - 什么导致运行时错误消息:std::system_error - 不允许操作,包括多线程?