//做了一个Timer的demo,但是发现cpu的利用率为100%,
//发现问题出现在while (true);能又更好的解决办法吗?保证能定时扫描,又能降低cpu利用率。
//谢谢!
import java.util.*;              
import java.lang.*;public class TimerTest
{
public static void main(String args[])
{
Timer timer = null;
        try {
            timer = new Timer(true);
            timer.schedule(new MyTimerTask(), 0 , 10000);
            System.out.println("while begin");
            while (true);
        } 
        finally {
         System.out.println("timer cancel begin");
            timer.cancel();
        }

    }

}class MyTimerTask extends TimerTask {

    public void run() {
    System.out.println("Scaner File Begin :" + Calendar.getInstance().getTime().toString()); 
    Scaner();
    } 
public void Scaner()
{
System.out.println("test begin");
}
        
}

解决方案 »

  1.   

    while(true); 这一语句是一个死循环,执行到这一句就不执行以下的语句了,结果什么都不执行,就在那里空转,你是想测试什么?
      

  2.   

    没有while (true)就不能实现定时扫描。
      

  3.   

    while(true)不是死循环啊。运行一下程序就知道我想测试定时扫描。
      

  4.   

    把while (true)换成下面的try{
    while (true)
    {
    Thread.sleep(1000000);
    }
    }catch(Exception e)
    {
    System.err.println(e.getMessage());
    }
      

  5.   

    楼主的用意是不想让程序结束, 上面的方法应该可以.我试了一下, CPU占用率非常低.
      

  6.   

    再问lei198203(lei)一个问题,在运行该程序的时候,用鼠标点击一下控制台界面后程序就暂停了。然后点击键盘任意键即可重新运行,不知道能不能让控制台的程序不暂停?谢谢。