【问题标题】:Is there any way to refer to, or convert a thread object as a string?有什么方法可以引用或将线程对象转换为字符串?
【发布时间】:2014-10-26 14:08:18
【问题描述】:

我目前正在使用基本上由我的讲师提供的 echo 服务器和 echo 客户端。每个客户端都连接到由 EchoServer 类中的 start() 启动的套接字线程。无论如何,我输入了“System.out.println(this);”这一行在服务器类的循环中。 值得庆幸的是,这给出了输出“Thread[Thread-0,5,main]”,“Thread[Thread-1,5,main]”,具体取决于它是哪个线程,分别是第一个或第二个。我想说:

if (this == "Thread[Thread-1,5,main]"){

do so and so
}else{
do so and so
}

但是“Thread[Thread-1,5,main]”不是字符串,所以有没有办法可以将当前线程称为字符串,或者如何引用或转换它?

也很抱歉没有分享代码,考虑到它属于我的讲师,我不确定它是否合法。

【问题讨论】:

  • 不比较字符串,为什么不比较java.lang.Thread的实例this

标签: java multithreading sockets


【解决方案1】:

我想你可能正在寻找Thread#getNameThread#setName

但是,正如 hexafraction 指出的那样,如果您有对线程的引用,则直接进行比较:

Thread t1 = new Thread(/*...*/);
Thread t2 = new Thread(/*...*/);

// ...later...

if (Thread.currentThread() == t1) {
    // It's t1
}

Thread.currentThread 返回对当前执行线程的引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    相关资源
    最近更新 更多