您的位置:首页 > 编程语言 > Java开发

java thread start run 的区别和联系

2014-12-27 21:11 169 查看
java thread start run 的区别和联系如下,摘取一段外文网站论坛上的解释,它讲的不错。一句话,run()是顺序执行而start()则是并行执行。

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: