少年阿賓

          那些青春的歲月

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
          public class Example{
              public static void main(String args[]){
                  A target=new A();    //線程thread的目標對象 
                  Thread thread=new Thread(target);
                  thread.setName("張三");
                  thread.start();
                  while(target.getStop()==false){}
                  System.out.println("我是主線程,負責恢復"+thread.getName()+"線程"); 
                  target.restart();  //恢復thread線程
              }

          class A implements Runnable{
              int number=0;
              boolean stop=false;
              boolean getStop(){
                      return stop;
              }
              public void run(){
                  while(true){
                      number++;
                      System.out.println(Thread.currentThread().getName()+"的number="+number);
                      if(number==3){
                          try{  System.out.println(Thread.currentThread().getName()+"被掛起");
                               stop=true;
                               hangUP();//掛起線程
                               System.out.println(Thread.currentThread().getName()+"恢復執行");
                          } 
                          catch(Exception e){}  
                      }
                      try{ Thread.sleep(1000); 
                      } 
                     catch(Exception e){}
                  }
              }
              public synchronized void  hangUP() throws InterruptedException{
                  wait();  
              }
              public synchronized void  restart(){
                  notifyAll();
              }
          }




          求教,main方法中的空循環是做什么用的?初學線程,不是很理解。
          while(target.getStop()==false){}
          等待target線程結束,target線程運行在主線程main里面,如果沒有這個空循環,主線程順序執行,target還沒有執行完得時候主線程已經執行完退出了,會導致target也退出。
          posted on 2012-11-17 01:38 abin 閱讀(1166) 評論(0)  編輯  收藏 所屬分類: JavaMultithread
          主站蜘蛛池模板: 雷波县| 玛纳斯县| 灵丘县| 丘北县| 赫章县| 高唐县| 长阳| 电白县| 黄大仙区| 永胜县| 石景山区| 东至县| 樟树市| 镇平县| 崇州市| 南充市| 桂东县| 湘潭市| 嵊州市| 柏乡县| 高碑店市| 德令哈市| 黎平县| 铅山县| 泊头市| 吴桥县| 个旧市| 徐水县| 鄯善县| 商城县| 静宁县| 蒙阴县| 和静县| 林西县| 开封县| 富宁县| 广南县| 札达县| 台北市| 尖扎县| 泽库县|