在一定时间后如何停止运行方法的执行?

时间:2019-12-24 05:27:14

标签: java

在一个类中,我有一个main方法和temp方法,我要从main方法调用temp方法,但是20秒后,我想停止这些方法的执行并再次开始调用temp方法。

我试图在代码中使用线程,但是它不起作用。

public static void main(){
  temp();   
 }

 public void temp(){
    // here is my code which takes some time more than 20 second to 
    // so i want to stop these method execution and call again temp method
 }

1 个答案:

答案 0 :(得分:0)

  

在单个线程中以可运行的方式运行temp方法。并在20秒后将其中断。捕获中断异常。

class TempThread implements Runnable { 

// to stop the thread 
private boolean exit; 

private String name; 
Thread t; 

TempThread(String threadname) 
{ 
    name = threadname; 
    t = new Thread(this, name); 
    exit = false; 
    t.start();
} 


public void run() 
{ 
    while (!exit) { 
        try { 
            Thread.sleep(100); 
        } 
        catch (InterruptedException e) { 
            System.out.println("Caught:" + e); 
        } 
    } 
} 


public void stop() 
{ 
    exit = true; 
} 
} 

现在在您的主类中等待20秒,然后调用stop()方法。不确定这里的临时方法是什么。

static void main(String[] args){

  TempThread t1 = new TempThread("runniing a temp"); 

  try{
    Thread.sleep(20000); //wait 20 seconds
  }catch (Exception e){
    e.printStackTrace();
  }
  t1.stop();
}
相关问题