有人可以解释一下为什么执行此程序后的输出如此不同吗?
首先,类:Thread扩展java.lang.Thread
public class UsingThreadExtension extends Thread {
public UsingThreadExtension(String s) {
super(s);
}
@Override
public void run() {
for (int i=0; i<5; i++) {
System.out.println(i + " " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
java.lang.Runnable的实现:
public class UsingRunnableImplementation implements Runnable {
@Override
public void run() {
for (int i=0; i<5; i++) {
System.out.println(i + " " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
主要课程:
public class ThreadsExample {
public static void main(String[] args) {
UsingThreadExtension threadA = new UsingThreadExtension("Thread A");
UsingRunnableImplementation runnableImplementation = new UsingRunnableImplementation();
Thread threadB = new Thread(runnableImplementation, "Thread B");
//threadA.start();
threadB.start();
try {
//threadA.join();
threadB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
//threadA.run();
threadB.run();
System.out.println("Main thread says hello!");
}
}
在这种组合中,输出是这样的:
0 Thread B
1 Thread B
2 Thread B
3 Thread B
4 Thread B
Main thread says hello!
在注释了threadB部分并取消注释threadA之后,有这样的事情:
0 Thread A
1 Thread A
2 Thread A
3 Thread A
4 Thread A
0 main
1 main
2 main
3 main
4 main
Main thread says hello!
有人可以告诉我,究竟是什么导致了这种差异?任何提示表示赞赏。我想,它与 threadA 中的覆盖 java.lang.Thread.run() 方法有关,但为什么 threadB 在第二种情况下不能运行?