我们知道在Java中可以通过继承一个Thread类来实现一个线程类,继承以后,需要重载run()
方法,但是在启动线程的时候则又是用start()
方法,这个是几个意思,启动直接用run()
不行么,我们试一下。
首先还是用start()
方法启动线程:
public class RunAndStart extends Thread{
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
RunAndStart thread1 = new RunAndStart();
RunAndStart thread2 = new RunAndStart();
thread1.start();
thread2.start();
}
}
输出结果:
Thread-1 0
Thread-0 0
Thread-1 1
Thread-0 1
Thread-0 2
Thread-1 2
Thread-0 3
Thread-1 3
Thread-1 4
Thread-0 4
跟我们想得差不多,再看下用run()
方法启动线程:
public class RunAndStart extends Thread{
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
RunAndStart thread1 = new RunAndStart();
RunAndStart thread2 = new RunAndStart();
thread1.run();
thread2.run();
}
}
输出结果:
main 0
main 1
main 2
main 3
main 4
main 0
main 1
main 2
main 3
main 4
看到这里,发现有点意思了啊,用start启动,我们看到的就是我们定义的线程,用run启动,那么我们看到的则是main线程,这是几个意思呢?
实际上是这样的,每个线程用start()
启动都是在独立的调用栈中进行的,而第二种情况调用run()
则是来自main线程的,我们在输出中已经看到了,run()
方法用的是当前的调用栈,而不是由新建的一个调用站。