简体   繁体   中英

How can I interrupt method execution by time?

Suppose method A is calling method B . Can method A control execution time of method B and interrupt it in, suppose, 60 seconds (method B can hangs for example)?

You can run tasks asynchronously using an ExecutorService , obtaining a Future that enables you to get the result of the task when it is done. There's a get method on the Future that you can call to wait for the answer, with a timeout. If it times out, you try to cancel the task by calling cancel on the Future .

ExecutorService executorService = Executors.newSingleThreadExecutor();

// Callable that has a run() method that executes the task
Callable<String> callable = ...;

// Submit the task for execution
Future<String> future = executorService.submit(callable);

try {
    String result = future.get(30, TimeUnit.SECONDS);
    System.out.println("Result: " + result);
}
catch (TimeoutException e) {
    System.out.println("Timeout");
    future.cancel(true);
}

There's a lot more to the concurrency API, see the package java.util.concurrent .

Could you describe what exactly do you want? Just stopping of execution method you can use return, System.exit() , last stop VM. By time, just check time and return from method. Also, you can try some reflection hacks... By the way, these are just a imagination if you will describe in more words what do you need I will help you.

Try:

public static void wait(int n){
    long time0,time1;
     time0=System.currentTimeMillis();
    do{
        time1=System.currentTimeMillis();
    }
    while (time1-time0<n);

}

I think that works. If you invoke this method, pass it with the amount of time in milliseconds you want the program to wait as parameter.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM