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

标签 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
 }

最佳答案

Run your temp method as runnable in a single thread. And interrupt it after 20 seconds. Catch the interrupt exception.

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();
}

关于java - 如何在一定时间后停止运行方法执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59464183/

相关文章:

java - 如何使用java检查Excel文件是否有更新

java - 合并排序交换和比较

java - 什么是 java.io.IOException : invalid header field?

java - minOccurs设置为0的XSD日期类型现在的值为“<xml-fragment…”(可设置为false)

java - 为 webapp 存储临时数据的最佳实践

java - 在 jersey 2.x 中,我收到类似 java.util.concurrent.ExecutionException 的错误

java - 拖放和调整元素大小

java - 如何将返回类型作为参数传递(无反射?)

java - 在 mapreduce 作业提交期间为 mappers 和 reducer 配置内存

Java,消化器 : stuck on this java. lang.NullPointerException