Thread的start与run

首先是java多线程编程核心技术里面有一个demo,让自己产生了一点疑问


public class MyThread extends Thread {
    public MyThread(){
        System.out.println("构造方法的打印 : "+Thread.currentThread().getName());
    }
    
    
    @Override
    public void run() {
        System.out.println("run 方法的打印 :"+Thread.currentThread().getName());
    }
}



public class Run {
        public static void main(String[] args) {
            MyThread myThread=new MyThread();
            myThread.setName("my");
            myThread.start();
            
//            myThread.run();
        }
}


可以看到构造方法是被主线程调用。run方法识别Thread-0 调用


public class Run {
        public static void main(String[] args) {
            MyThread myThread=new MyThread();

     //   
       myThread.start();
            
        myThread.run();
        }
}

可以看到构造方法和run都是main线程调用


public class Run {
        public static void main(String[] args) {
            MyThread myThread=new MyThread();
            myThread.setName("my");
            myThread.start();
            
//            myThread.run();
        }
}

可以看到 start方法就是当前线程(主)启动   “my”线程 ,然后my线程执行run方法

而run则是直接由当前线程(主)执行 “my”线程的run方法(与调用普通方法相同);

jdk中的api start方法

 * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.

大致意思是说。会导致这个线程与其他线程同时执行//省略...


run方法:

 /**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.


大致意思就是 如果会调用  这个thread构造方法的runnable对象run方法 // ....











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值