【问题标题】:How to stop running method execution after a certain time period? [duplicate]如何在一段时间后停止正在运行的方法执行? [复制]
【发布时间】:2020-04-15 06:22:21
【问题描述】:

在一个类中,我有一个 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
 }

【问题讨论】:

  • 您是否可以简单地将temp(); 作为可运行对象运行,然后在您的主类等待20 秒后终止它?在 while 循环中执行此操作
  • 你能解释一下吗,因为main方法中还有一些其他代码
  • 在不知道你的 temp() 方法是什么的情况下,我发布了一个简单的线程类,它看起来对你很有希望。
  • 在临时方法中,我已经生成了一个数字,它需要更多时间来匹配我的条件,但我不想等待超过 20 或 10 秒,然后再次调用该方法并生成其他数字跨度>

标签: java


【解决方案1】:

在单个线程中运行您的 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();
}

【讨论】:

  • 但是我应该把我的临时方法代码放在哪里
  • run 方法中。这只是如何做到这一点的一个示例。还有很多其他方法,包括使用Future.get(timeout in seconds)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 2011-05-14
  • 2011-05-18
  • 2015-12-29
  • 1970-01-01
相关资源
最近更新 更多