少年阿賓

          那些青春的歲月

            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
          主站蜘蛛池模板: 千阳县| 紫阳县| 竹山县| 唐海县| 怀柔区| 鱼台县| 历史| 中山市| 金平| 太康县| 海口市| 奇台县| 高淳县| 明溪县| 鄄城县| 江陵县| 德安县| 上蔡县| 潍坊市| 庆安县| 抚顺市| 黑山县| 乌鲁木齐县| 古田县| 北票市| 中西区| 渑池县| 泰兴市| 黄陵县| 淅川县| 汉中市| 齐河县| 读书| 招远市| 永宁县| 桦川县| 沾化县| 灵川县| 潞西市| 图木舒克市| 黑山县|