run和start方法,有时候会被当成起一个新的线程执行代码逻辑,来达到程序异步执行的效果。
(1)程序调用run方法:
public class ExtendThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
try {
//打印出线程数
System.out.println("run方法打印线程数:"+Thread.currentThread().activeCount());
Thread.sleep(2000);
System.out.println("ExtendThread run over");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ExtendThread thread = new ExtendThread();
thread.run();//调用run方法
//thread.start();//调用start方法
//打印出线程数
System.out.println("main方法打印线程数:"+Thread.currentThread().activeCount());
}
}
运行结果:
run方法打印线程数:1
ExtendThread run overmain方法打印线程数:1
结论: 1.调用run方法,不会起新的线程;
2.程序模块同步执行,先执行ExtendThread的run方法,再输出主程序main方法的打印信息。
(2)程序改调用start方法
public class ExtendThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
try {
//打印出线程数
System.out.println("run方法打印线程数:"+Thread.currentThread().activeCount());
Thread.sleep(2000);
System.out.println("ExtendThread run over");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ExtendThread thread = new ExtendThread();
//thread.run();//调用run方法
thread.start();//调用start方法
//打印出线程数
System.out.println("main方法打印线程数:"+Thread.currentThread().activeCount());
}
}
运行结果:
main方法打印线程数:2
run方法打印线程数:2
ExtendThread run over
结论: 1.调用start方法,会起新的线程;
2.程序模块异步执行,同时执行ExtendThread的run方法,和输出主程序main方法的打印信息。
(3)其实,从start源码方法注释可以得出以下三点结论:
1.main方法调用start方法,会让java虚拟机调用run方法。
2.start的执行结果,是会有两个在跑的线程,意思就是会新启动一个线程
3.start方法不能连续调用多次,否则会报java.lang.IllegalThreadStateException异常。
而调用run方法,则只是调用重写的run方法,不会重启线程
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
public synchronized void start(){
/** 略**/
}