问答题 run()方法与start()方法有什么区别
【正确答案】
【答案解析】通常,系统通过调用线程类的start()方法来启动一个线程,此时该线程处于就绪状态,而非运行状态,也就意味着这个线程可以被JVM来调度执行。在调度过程中,JVM通过调用线程类的run()方法来完成实际的操作,当run()方法结束后,此线程就会终止。
如果直接调用线程类的run()方法,这会被当作一个普通的函数调用,程序中仍然只有主线程这一个线程,也就是说,start方法()能够异步地调用run()方法,但是直接调用run()方法却是同步的,因此也就无法达到多线程的目的。
由此可知,只有通过调用线程类的start()方法才能真正达到多线程的目的。下面通过一个例子来说明说明run()方法与start()方法的区别。
class ThreadDemo extends Tbread{
@Override
public void run(){
System.out.println("ThreadDemo:begin");
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("ThreadDemo:end");
}
}
public class Test{
public static void test1(){
System.out.println("test1:begin");
Thread t1=new ThreadDemo();
t1.start();
System.out.println("test1:end");
}
public static void test2(){
System.out.println("test2:begin");
Thread t1=new ThreadDemo();
t1.run();
System.out.println("test2:end");
}
public static void main(String[]args){
test1();
try{
Thread.sleep(5000);
}catch(InterruptedException e){
//TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println();
test2();
}
}
程序运行结果为:
test1:begin
test1:end
ThreadDemo:begin
ThreadDemo:end
test2:begin
ThreadDemo:begin
ThreadDemo:end
test2:end
从test1的运行结果可以看出,线程t1是在test1方法结束后才执行的(System.out.println("test1:end")语句不需要等待t1.start()运行结果就可以执行),因此,在test1中调用start()方法是异步的,所以main线程与t1线程是异步执行的。从test2的运行结果可以看出,调用t1.run()是同步的调用方法,因为System.out.println("test2:end")只有等t1.run()调用结束后才能执行。