【发布时间】:2015-12-22 06:54:45
【问题描述】:
我正在学习 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() 那么一切都按预期工作。它们之间有什么区别?
【问题讨论】:
标签: java multithreading