首页 > 技术文章 > java中自定义线程中调用run()方法和start()方法的区别

thinker001 2019-10-15 14:36 原文

  1. 当Test2 中调用start()方法的时候,构造方法由调用线程由main执行,run方法由自身线程Thread-0执行,线程name输出结果:
       
  1. 当Test2 中调用run()方法的时候,都是main中的线程在执行,它存在调用程序的线程中而不是它自身的线程,也就是java虚拟机中的线程,线程name输出结果:
        (线程的run()方法是由java虚拟机直接调用的,如果我们没有启动线程(没有调用线程的start()方法)而是在应用代码中直接调用run()方法,那么这个线程的run()方法其实运行在当前线程(即run()方法的调用方所在的线程)之中,而不是运行在其自身的              线程中,从而违背了创建线程的初衷
 
       
 
 
 
public class Test2 {

public static void main(String[] args){
Test t= new Test();
t.run();//t.start();
}
}

 

 
public class Test2 {
 
public static void main(String[] args){
Test t= new Test();
t.run();//t.start();
}
}
 
public class Test extends Thread {
 
public Test() {
System.out.println("构造方法():" + Thread.currentThread().getName() );
}
 
public void run() {
System.out.println("run():" + Thread.currentThread().getName() );
}
 
}

 

推荐阅读