Thread类中run和start的区别(方法及运行结果)

start() 和 run()的区别说明

start() : 它的作用是启动一个新线程,新线程会执行相应的run()方法。start()不能被重复调用。
run() : run()就和普通的成员方法一样,可以被重复调用。单独调用run()的话,会在当前线程中执行run(),而并不会启动新线程!

以代码实例进行说明

class MyThread extends Thread{
public void run(){

}
};
MyThread mythread = new MyThread();
mythread.start()会启动一个新线程,并在新线程中运行run()方法。
而mythread.run()则会直接在当前线程中运行run()方法,并不会启动一个新线程来运行run()。

start() 和 run()的区别示例

 class MyThread extends Thread{  
    public MyThread(String name) {
        super(name);
      }
 
    public void run(){
         System.out.println(Thread.currentThread().getName()+" is running");
    } 
 }


 public class Demo {  
     public static void main(String[] args) {  
         MyThread mythread=new MyThread("mythread");

        System.out.println(Thread.currentThread().getName()+" call mythread.run()");
         mythread.run();
 
         System.out.println(Thread.currentThread().getName()+" call mythread.start()");
        mythread.start();
     }  
 }



//运行结果

main call mythread.run()
main is running 
main call mythread.start()
mythread is running

(1)Thread.currentThread().getName()是用于获取“当前线程”的名字。当前线程是指正在cpu中调度执行的线程。
(2) mythread.run()是在“主线程main”中调用的,该run()方法直接运行在“主线程main”上
(3) mythread.start()会启动“线程mythread”,“线程mythread”启动之后,会调用run()方法;此时的run()方法是运行在“线程mythread”上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值