黑马程序员技术交流社区
标题: 线程的执行,run,start。 [打印本页]
作者: 木木赤赤 时间: 2013-11-26 10:01
标题: 线程的执行,run,start。
本帖最后由 木木赤赤 于 2013-11-26 10:59 编辑
class Demo extends Thread
{
publicvoid run()
{
for(intx=0; x<60;x++)
System.out.println("demorun--"+x);
}
}
class ThreadDemo
{
publicstatic void main(String[] args)
{
Demod= new Demo();
d.start();
//d,run
for(intx=0; x<60;x++)
System.out.println("hello--"+x);
}
}
直接调用d.run();方法,和通过d.start();调用run方法有什么区别,都会产生什么效果?
作者: 爱上这格调 时间: 2013-11-26 10:05
直接调用run是不会开启多线程的 调用start方法 会调用系统底层开启多线程
所以要开启多线程 就要通过start方法
作者: 李文帅 时间: 2013-11-26 10:16
Start用于开启线程,Run用于存储要运行的代码
1) start:
用start方法来启动线程,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而直接继续执行下面的代码。通过调用Thread类的start()方法来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,一旦得到spu时间片,就开始执行run()方法,这里方法run()称为线程体,它包含了要执行的这个线程的内容,Run方法运行结束,此线程随即终止。
2) run:
run()方法只是类的一个普通方法,如果直接调用Run方法,程序中依然只有主线程这一个线程,其程序执行路径还是只有一条,还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码,这样就没有达到写线程的目的。
作者: 回天之力 时间: 2013-11-26 10:19
直接调用Thread的子类Demo ,中的run方法,不会生成一个线程,他只是向平常的类之间的方法调用一样。而用new Demo().start(),这样会启动一个新线程,而且在运行时,jvm会在内部自动调用Demo中的run方法。
作者: 忄雾飞扬 时间: 2013-11-26 10:19
- public class Test{
- public static void main(String[] args){
- //这句话是你在创建一个Demo实例对象
- Demo d= new Demo();
- //。start()是java中开启一条新的运行线程的方法,从某中意义上讲是和主线程并行运行的
- d.start();
- //。run()则是普通的对象调用本身类型的类中定义的函数(方法)而没有开启一条新的工作线程是在主线程中按由上到下的顺序执行的
- d.run();
- //下面的代码自然不用说,也是在主线程中按由上至下的顺序执行的
- for(int x=0; x<60;x++)
- System.out.println("hello--"+x);
- }
- }
- //自定义了一个线程
- class Demo extends Thread{
- public void run(){
- for(int x=0; x<60;x++)
- System.out.println("demorun--"+x);
- }
- }
复制代码
作者: freehiker 时间: 2013-11-26 10:26
通过run方法不能创建线程,在Thread类源码中,run方法只是一个普通的方法,不能在JVM中创建线程,而是通过start()方法开启一个线程,start()方法内部是通过group.add()的方法将线程加入到group中,若group不为null,JVM就会启动group中的线程
附上源码:
- public synchronized void start() {
- /**
- * This method is not invoked for the main method thread or "system"
- * group threads created/set up by the VM. Any new functionality added
- * to this method in the future may have to also be added to the VM.
- *
- * A zero status value corresponds to state "NEW".
- */
- if (threadStatus != 0)
- throw new IllegalThreadStateException();
- /* Notify the group that this thread is about to be started
- * so that it can be added to the group's list of threads
- * and the group's unstarted count can be decremented. */
- group.add(this);
- boolean started = false;
- try {
- start0();
- started = true;
- } finally {
- try {
- if (!started) {
- group.threadStartFailed(this);
- }
- } catch (Throwable ignore) {
- /* do nothing. If start0 threw a Throwable then
- it will be passed up the call stack */
- }
- }
- }
复制代码
作者: 肖川 时间: 2013-11-26 10:45
run方法里面放的是多线程需要执行的代码。规定就是这么写的。调用start方法会自动执行run方法里面的代码。没有听说过直接调用run方法这种。人家线程的运行机制就是这么设计的
作者: 王雷1 时间: 2013-11-26 11:12
最简单的说就是你调用run方法,就是调用run方法了,什么都没有,但是你调用start方法的意思是说,你要开启线程,并执行run方法。一个是调用普通方法,一个是开启线程并执行此特定方法。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |