当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《无法在java中设置线程的名称》经验,为你挑选了1个好方法。

我正在学习Java中的Thread并且有一个像这样的小程序.我创建一个线程并使用它来创建另一个线程.但是我无法更改第二个线程的名称.任何人都可以解释为什么会这样吗?另外,Thread.sleep(100)表示主线程将休眠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(),那么一切都按预期工作.它们之间有什么区别?



1> YoungHobbit..:
   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

另外,Thread.sleep(100)表示主线程将休眠100毫秒是否正确.

是.那是正确的.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.
.....
}
....
....
}

推荐阅读
刘美娥94662
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有