Thread继承类中的run()方法和start()方法的区别

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mythread.www;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class Run {
    public static void main(String[] args){
        MyThread thread=new MyThread();
        thread.setName("myThread");
        thread.run();
        for(int i=0;i<10;i++){
            try {
                int time=(int)(Math.random()*1000);
                Thread.sleep(time);
                System.out.println("main="+Thread.currentThread().getName());
            } catch (InterruptedException ex) {
                Logger.getLogger(Run.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

      这两者大有讲究。

      在高洪岩先生所著《Java多线程编程核心技术》第6页上,对Thread继承类中的start()和run()方法的区别曾经做过解释:

      Thread.java类中的start()方法通知“线程管理器”(原书是线程规划器,鄙人觉得线程管理器这一称谓更贴切些)此线程已经准备就绪,等待调用线程对象的run()方法。这个过程实际上就是让系统安排一个时间来调用Thread中的run()方法,也就是使线程得到运行,启动线程,具有异步的效果。如果调用代码thread.run()就不是异步执行了,而是同步,那么此对象并不交给“线程处理器”来处理,而是由main主线程来调用run()方法,也就是必须等run()方法中的代码执行完之后才可以执行后面的代码。

package com.mythread.www;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class MyThread extends Thread{

    @Override
    public void run(){
        for(int i=0;i<10;i++){
            int time=(int)(Math.random()*1000);
            try {
                Thread.sleep(time);
            } catch (InterruptedException ex) {
                Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("run="+Thread.currentThread().getName());
        }
    }
}

 http://blog.csdn.net/xuxurui007/article/details/7685076

上面链接中的文章是一篇相关文章,希望对大家有所帮助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章