java 线程start和run的区别

java中thread的start()和run()的区别:

1.start()方法来启动线程,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而直接继续执行下面的代码:

通过调用Thread类的start()方法来启动一个线程,
这时此线程是处于就绪状态,
并没有运行。
然后通过此Thread类调用方法run()来完成其运行操作的,
这里方法run()称为线程体,
它包含了要执行的这个线程的内容,
Run方法运行结束,
此线程终止,
而CPU再运行其它线程,

 

2.run()方法当作普通方法的方式调用,程序还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码:

而如果直接用Run方法,
这只是调用一个方法而已,
程序中依然只有主线程--这一个线程,
其程序执行路径还是只有一条,
这样就没有达到写线程的目的。

 

举例说明一下:

记住:线程就是为了更好地利用CPU,
提高程序运行速率的!

public class TestThread1{
public static void main(String[] args){
Runner1 r=new Runner1();
//r.run();//这是方法调用,而不是开启一个线程
Thread t=new Thread(r);//调用了Thread(Runnable target)方法。且父类对象变量指向子类对象。
t.start();

for(int i=0;i<100;i++){
System.out.println("进入Main Thread运行状态");
System.out.println(i);
}
}
}
class Runner1 implements Runnable{ //实现了这个接口,jdk就知道这个类是一个线程
public void run(){

for(int i=0;i<100;i++){
System.out.println("进入Runner1运行状态");
System.out.println(i);
}
}
}

同时摘取一段外文网站论坛上的解释:
Why do we need start() method in Thread class? In Java API description for Thread class is written : "Java Virtual Machine calls the run method of this thread..".

Couldn't we call method run() ourselves, without doing double call: first we call start() method which calls run() method? What is a meaning to do things such complicate?

 

 

There is some very small but important difference between using start() and run() methods. Look at two examples below:

Example one:

Code:

Thread one = new Thread();
Thread two = new Thread();
one.run();
two.run();

Example two:

Code:

Thread one = new Thread();
Thread two = new Thread();
one.start();
two.start();

The result of running examples will be different.

In Example one the threads will run sequentially: first, thread number one runs, when it exits the thread number two starts.

In Example two both threads start and run simultaneously.

Conclusion: the start() method call run() method asynchronously (does not wait for any result, just fire up an action), while we run run() method synchronously - we wait when it quits and only then we can run the next line of our code.

 

http://blog.csdn.net/tornado886/archive/2009/09/06/4524346.aspx

 

 

Thread对象的run()方法在一种循环下,使线程一直运行,直到不满足条件为止,在你的main()里创建并运行了一些线程,调用Thread类的start()方法将为线程执行特殊的初始化的过程,来配置线程,然后由线程执行机制调用run()。如果你不调用start()线程就不会启动。

 

 

因为线程调度机制的行为是不确定的,所以每次运行该程序都会有不同的结果,你可以把你的循环次数增多些,然后看看执行的结果,你会发现main()的线程和Thread1是交替运行的。
4.还有就是尽管线程的调度顺序是不固定的,但是如果有很多线程被阻塞等待运行,调度程序将会让优先级高的线程先执行,而优先级低的线程执行的频率会低一些。

 

 

线程的启动是比较复杂的,需要为线程分配资源,它的START方法被调用时系统才会为线程分配资源。
你上面调用线程的run方法只能算普通的方法调用一样,得运行完run里面的代码整个程序才能往下进行,而如果调用start方法,线程和MAIN方法就会抢资源,打印的语句会交替出现,你把线程里的循环次数加到300,试一下依次调run、start和两次都调start方法时所出现的情况应该能看出点端倪~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值