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

上面鏈接中的文章是一篇相關文章,希望對大家有所幫助。

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