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

来源:互联网 发布:linux系统上网 编辑:程序博客网 时间:2024/05/17 06:37
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.
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 用完权健洁净宝后奇痒的厉害怎么办 老房子铸铁暖气管从外锈蚀了怎么办 德意壁挂炉补水多了水压过高怎么办 新空调的散热片铜管漏了怎么办 猪舍被别人推掉漏电电到人怎么办? 网上买的燃气灶连接用软管怎么办 哈弗h3后减振器上支架坏了怎么办 汽车用收录机电机皮带断了怎么办 大便太粗把马桶堵了怎么办 大便过粗把马桶堵了怎么办 大便硬的像石头拉不出来怎么办 家里埋在地下的水管漏水怎么办 埋在墙里的水管漏水怎么办 开发商暗埋水管热熔接头漏水怎么办 钻墙把水管钻破了怎么办 钻墙时不小心把水管钻破了怎么办 孩子把同桌的铅笔盒弄坏了怎么办 水管伐坏了物业不给修怎么办 卫生间埋在地下的水管漏水怎么办 埋在地下的水管冻住了怎么办 洗脸盆下水管有眉笔掉堵了怎么办 楼上打空调眼导致墙面潮湿怎么办 阳台做防水了又贴砖还漏水怎么办 洗菜盆里的盖子吸住拔不起来怎么办 掉小区阴井盖里物业不管怎么办 卫生间下水道被头发堵了怎么办妙招 久量时尚夜光台灯不亮了怎么办 我想做水电暖工程没有资质怎么办 修手机被弄丢了没有开维修单怎么办 手机去维修被老板弄丢了怎么办 5年保修期过后房子楼顶漏水怎么办 墙内水管漏水怎么办3步骤巧维修 下面有地暖下面水管漏水怎么办 热水器接的塑料水管子漏水怎么办 电热水器烧热水时热水管漏水怎么办 户户通位置锁定模块异常1怎么办 户户通位置锁定模块异常3怎么办 逆战安全系统检测客户端异常怎么办 电视户户通位置信息模块异常怎么办 苹果手机wi-fi模块坏了怎么办 xp本地连接受限制或无连接怎么办