<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    posts - 110, comments - 101, trackbacks - 0, articles - 7
      BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

    java 多線程中 start 與run 的區別

    Posted on 2011-11-08 20:53 云云 閱讀(2799) 評論(0)  編輯  收藏
    class NewThread implements Runnable {
    Thread t;
    public NewThread() {
    t = new Thread(this,"Demo thread");
    System.out.println("Child thread : " + t);
    t.run();
    }
    public void run(){
    try{
    for( int i = 5; i > 0; i --){
    System.out.println("Child thread :" + i);
    Thread.sleep(500);
    }

    }catch(InterruptedException e){
    System.out.println("Child interrupted.");
    }
    System.out.println("Exiting child thread.");

    }
    }

    public class TestDemo{
    public static void main(String args[]){
    new NewThread();
    try{
    for( int i = 5; i > 0; i --){
    System.out.println("Main thread :" + i);
    Thread.sleep(1000);
    }
    }catch(InterruptedException e){
    System.out.println("Main interrupted.");
    }
    System.out.println("Exiting Main thread.");
    }
    }

    這是一個實現多線程的程序,運行結果如下:
    Child thread : Thread[Demo thread,5,main]
    Main thread :5
    Child thread :5
    Child thread :4
    Main thread :4
    Child thread :3
    Child thread :2
    Main thread :3
    Child thread :1
    Exiting child thread.
    Main thread :2
    Main thread :1
    Exiting Main thread.

    試想,如果把 start()改成run()會出現什么結果?
    修改之后運行結果:
    Child thread : Thread[Demo thread,5,main]
    Child thread :5
    Child thread :4
    Child thread :3
    Child thread :2
    Child thread :1
    Exiting child thread.
    Main thread :5
    Main thread :4
    Main thread :3
    Main thread :2
    Main thread :1
    Exiting Main thread.
    程序運行成為了單線程順序執行。為什么?
    start方法:用來啟動一個線程, 這時此線程是處于就緒狀態, 并沒有運行。 然后通過此Thread類調用方法run()來完成其運行操作的, 這里方法run()稱為線程體, 它包含了要執行的這個線程的內容, run方法運行結束, 此線程終止, 而CPU再運行其它線程,
    直接用run方法: 這只是調用一個方法而已, 程序中依然只有主線程--這一個線程, 其程序執行路徑還是只有一條, 這樣就沒有達到寫線程的目的。
    記住:線程就是為了更好地利用CPU,提高程序運行速率的!

    只有注冊用戶登錄后才能發表評論。


    網站導航:
     
    主站蜘蛛池模板: 亚洲色欲色欲www在线丝| 午夜视频在线免费观看| 成人毛片视频免费网站观看| 亚洲欧美日韩国产成人| 成人性生交视频免费观看| 免费看美女午夜大片| 91亚洲国产成人精品下载| 亚洲精品视频免费看| 国产亚洲男人的天堂在线观看 | 99视频免费播放| 国产成人精品日本亚洲语音| 国产精品亚洲综合一区在线观看| 亚洲国产成人影院播放| 91免费国产精品| 一级毛片a免费播放王色 | 精品视频免费在线| 亚洲国产美女在线观看| 亚洲一区日韩高清中文字幕亚洲| 日本免费电影一区| 美女内射毛片在线看免费人动物| 24小时日本韩国高清免费| 香港一级毛片免费看| 亚洲天堂一区在线| 亚洲综合无码一区二区三区| 在线亚洲精品福利网址导航| 免费大香伊蕉在人线国产| 8x成人永久免费视频| 57pao国产成视频免费播放| 18pao国产成视频永久免费| 三上悠亚电影全集免费| 色妞www精品视频免费看| 亚洲AV女人18毛片水真多| 直接进入免费看黄的网站| 免费看一级高潮毛片| 一级特级aaaa毛片免费观看| 欧亚一级毛片免费看| 一区二区三区免费电影| 国产偷国产偷亚洲清高APP| 亚洲AV无码专区在线观看成人| 久久久久久久久无码精品亚洲日韩| 亚洲中文字幕一二三四区|