Thread类:run和start方法的区别

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 over

main方法打印线程数: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(){

        /** 略**/

    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值