少年阿賓

          那些青春的歲月

            BlogJava :: 首頁(yè) :: 聯(lián)系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
          public class Example{
              public static void main(String args[]){
                  A target=new A();    //線程thread的目標(biāo)對(duì)象 
                  Thread thread=new Thread(target);
                  thread.setName("張三");
                  thread.start();
                  while(target.getStop()==false){}
                  System.out.println("我是主線程,負(fù)責(zé)恢復(fù)"+thread.getName()+"線程"); 
                  target.restart();  //恢復(fù)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()+"恢復(fù)執(zhí)行");
                          } 
                          catch(Exception e){}  
                      }
                      try{ Thread.sleep(1000); 
                      } 
                     catch(Exception e){}
                  }
              }
              public synchronized void  hangUP() throws InterruptedException{
                  wait();  
              }
              public synchronized void  restart(){
                  notifyAll();
              }
          }




          求教,main方法中的空循環(huán)是做什么用的?初學(xué)線程,不是很理解。
          while(target.getStop()==false){}
          等待target線程結(jié)束,target線程運(yùn)行在主線程main里面,如果沒(méi)有這個(gè)空循環(huán),主線程順序執(zhí)行,target還沒(méi)有執(zhí)行完得時(shí)候主線程已經(jīng)執(zhí)行完退出了,會(huì)導(dǎo)致target也退出。
          posted on 2012-11-17 01:38 abin 閱讀(1162) 評(píng)論(0)  編輯  收藏 所屬分類(lèi): JavaMultithread
          主站蜘蛛池模板: 疏附县| 云浮市| 南汇区| 镇赉县| 兴义市| 商丘市| 荣昌县| 开江县| 会昌县| 乌恰县| 丹东市| 宽甸| 延津县| 唐海县| 尤溪县| 汕头市| 车致| 汾西县| 新昌县| 和平县| 七台河市| 新蔡县| 丹棱县| 巫山县| 新化县| 惠水县| 贡觉县| 喜德县| 乃东县| 郓城县| 高安市| 毕节市| 景德镇市| 驻马店市| 五原县| 中山市| 阿拉善右旗| 墨江| 邵阳县| 剑川县| 林口县|