如何控制一个方法最多运行1分钟,比如说,累Example里面又个方法 doLoop,这个方法可能是个死循环,我如何控制他最多运行1分钟,如何用线程来实现?谢谢了。

解决方案 »

  1.   

    http://blog.csdn.net/CrazyGou/archive/2007/06/12/1648475.aspx
      

  2.   

    在Example里面加
    new Timer().schedule(new TimeTask{
    public void run(){
    doLoop();
    }
    },60000);
      

  3.   

    更正一下,应该这样
    public class Example extends Thread{
    public Example(){
    start();
    }
    public void run(){
    try{
    doloop();
    }catch(InterruptedException e){
    System.out.println("Stop");
    }
    }
    public static void main(String[] args){
    Example ex = new Example();
    new Timer().schedule(new TimeTask{
    public void run(){
    ex.interrupt();
    }
    },60000);
    }
    }
      

  4.   

    Timer里面的类应该是TimerTask
    doloop的方法内容我把它给省略了
      

  5.   

    import java.util.Timer;
    import java.util.TimerTask;
    public class Example {
    Timer timer = new Timer();
    int seconds;
    Example(int seconds) {
    this.seconds = seconds;
    }
    public void doLoop() { }
    public void start() {
    doLoop();
    timer.schedule(new TimerTask() {
    public void run() {
    timer.cancel();
    }
    }, seconds * 1000); }
    public static void main(String[] args) {
    Example example = new Example(60);
    example.start();
    }}
      

  6.   

    在循环前边定义一个变量boolean  = false
    调用一个线程,一分钟之后把设为true
    开始循环,判断为true时跳出
      

  7.   

    public static void main(String[] args) throws Exception{
        Example ex = new Example();//example类要继承Thread
        ex.start();//开一个线程
        sleep(60000);
        System.exit(0);//你可以试一下!
    }