gpt4 book ai didi

java - 无法在java中设置线程名称

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:53 25 4
gpt4 key购买 nike

我正在学习 Java 中的线程并且有一个像这样的小程序。我创建一个线程并使用它来创建另一个线程。但是我不能更改第二个线程的名称。谁能解释为什么会这样?另外,Thread.sleep(100) 意味着主线程将 hibernate 100 毫秒是否正确。谢谢。

class Thread1 extends Thread{
public void run() {
for(int i=0;i<5;i++){
System.out.println(getName()+" is running. Time is "+i);
}
}
}

public class Program{
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread1();
t1.setName("Thread 1");
Thread t2 = new Thread(t1);
t2.setName("Thread 2");
t1.start();
Thread.sleep(100);
t2.start();
}
}

这个程序的结果是:

Thread 1 is running. Time is 0
Thread 1 is running. Time is 1
Thread 1 is running. Time is 0
Thread 1 is running. Time is 1

编辑:如果我将 getName() 更改为 Thread.currentThread().getName(),那么一切都会按预期工作。它们之间有什么区别?

最佳答案

   Thread t1 = new Thread1();
t1.setName("Thread 1");
Thread t2 = new Thread(t1); <--- See this.

您正在将先前创建的相同线程实例 (t1) 传递给下一个线程实例 (t2)。这就是为什么会出现同名的原因。

本来应该是这样的:

   Thread t2 = new Thread1();
t2.setName("Thread 2");

输出:

Thread 1 is running. Time is 0
Thread 1 is running. Time is 1
Thread 1 is running. Time is 2
Thread 1 is running. Time is 3
Thread 1 is running. Time is 4
Thread 2 is running. Time is 0
Thread 2 is running. Time is 1
Thread 2 is running. Time is 2
Thread 2 is running. Time is 3
Thread 2 is running. Time is 4

Also, is it correct that Thread.sleep(100) means the main thread will sleep for 100 msec.

是的。那是对的。 Thread.sleep(milliseconds) 以毫秒为单位获取参数。


当您在创建 Thread 对象时传递 Thread 实例。这个新线程将使用传递的实例来执行(作为 Runnable 实例)。这就是为什么你得到 Thread 1 并且运行的线程不同,新创建的线程实例。所以 Thread.currentThread().getName() 会给你你设置的名字。

public class Thread implements Runnable {
....
....

/* What will be run. */
private Runnable target; // <-- Runnable is defined here for the thread.


public Thread(Runnable target) { //<-- constructor you are calling.
init(null, target, "Thread-" + nextThreadNum(), 0); //<-- internal init call.
}

private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
init(g, target, name, stackSize, null); //<-- internal init call.
}

private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
.....
.....
this.target = target; // <-- Set the Runnable for the thread.
.....
}
....
....
}

关于java - 无法在java中设置线程名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34410060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com