posts - 110, comments - 101, trackbacks - 0, articles - 7
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理
          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.");
          }
          }

          這是一個(gè)實(shí)現(xiàn)多線程的程序,運(yùn)行結(jié)果如下:
          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()會(huì)出現(xiàn)什么結(jié)果?
          修改之后運(yùn)行結(jié)果:
          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.
          程序運(yùn)行成為了單線程順序執(zhí)行。為什么?
          start方法:用來啟動(dòng)一個(gè)線程, 這時(shí)此線程是處于就緒狀態(tài), 并沒有運(yùn)行。 然后通過此Thread類調(diào)用方法run()來完成其運(yùn)行操作的, 這里方法run()稱為線程體, 它包含了要執(zhí)行的這個(gè)線程的內(nèi)容, run方法運(yùn)行結(jié)束, 此線程終止, 而CPU再運(yùn)行其它線程,
          直接用run方法: 這只是調(diào)用一個(gè)方法而已, 程序中依然只有主線程--這一個(gè)線程, 其程序執(zhí)行路徑還是只有一條, 這樣就沒有達(dá)到寫線程的目的。
          記住:線程就是為了更好地利用CPU,提高程序運(yùn)行速率的!

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 交口县| 佛山市| 慈利县| 云阳县| 景宁| 和田市| 舒城县| 土默特右旗| 伊宁县| 内乡县| 高陵县| 盘锦市| 安庆市| 洪雅县| 紫云| 怀来县| 公安县| 府谷县| 巴里| 抚顺县| 哈尔滨市| 佛冈县| 平潭县| 上饶市| 桂阳县| 龙南县| 平定县| 黑山县| 嘉义县| 兴安县| 公主岭市| 土默特右旗| 丁青县| 湖南省| 阿拉善左旗| 镇巴县| 同江市| 平江县| 金沙县| 神池县| 新余市|