2013-12-11 60 views
0

在下面的示例程序中,我需要ThreadCountcount.sleep()調用30000 ms時應暫停寫入控制檯,並且它應發生在每個時間間隔1000 ms。當我運行程序時,寫入控制檯並沒有停止。它連續打印而不用等待30000 ms。請幫我理解發生了什麼問題。如何暫停Thread的執行?

什麼是在每個時間間隔內停止ThreadCount特定時間段的解決方案?

import java.util.Timer; 
import java.util.TimerTask; 

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
/** 
* 
* @author admin 
*/ 
public class Test { 

    Test() { 
     Count count = new Count(); 
     count.start(); 
     TimerTask task = new RunMeTask(count); 
     Timer timer = new Timer(); 
     timer.schedule(task, 1000, 60000); 
    } 

    public static void main(String[] argu) { 
     Test test = new Test(); 

    } 

    public class Count extends Thread { 

     @Override 
     public void run() { 
      int i = 0; 
      do { 
       System.out.println(i++); 
      } while (true); 
     } 
    } 

    public class RunMeTask extends TimerTask { 

     private final Count count; 

     RunMeTask(Count count) { 
      this.count = count; 
     } 

     @Override 
     public void run() { 
      synchronized (count) { 
       try { 
        count.wait(30000); 
       } catch (InterruptedException ex) { 
        System.out.println(ex.toString()); 
       } 
      } 
     } 
    } 
} 
+0

它將很容易使用Thread.sleep。並btw等待與通知一起使用。谷歌等待並通知示例 – qwr

+1

請參閱:http://stackoverflow.com/questions/20516223/avoiding-wait-notify-in-a-utility-to-suspend-resume-threads – TwoThe

回答

0

RunMeTask線程將不等待Count。兩個線程都是分開的,並分別執行。