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