This is a sample that executes a specific process in Java in another thread. When an infinite loop occurs in a certain process (when the process is not completed within the specified time), it is necessary to interrupt the process and generate an error, so it is a memorandum at that time.
main.java
package main;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Main {
public static void main(String[] args) {
int a = 1;
int b = 2;
int c = 3;
ExecutorService exec = Executors.newSingleThreadExecutor();
//Execute processing in another thread
Future<Integer> future = exec.submit(new ExcutorSample(a, b, c));
Integer result = 0;
try{
//Wait 10 seconds. If the process ends correctly, the calculation result will be returned. Throw an exception after 10 seconds
result = future.get(10, TimeUnit.SECONDS);
} catch(TimeoutException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
//Suspend processing. This process is harmless even if the process is completed normally.
future.cancel(true);
}
System.out.println(result);
}
public static class ExcutorSample implements Callable<Integer>{
private int a;
private int b;
private int c;
public ExcutorSample(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
@Override
public Integer call() throws Exception {
//Built-in infinite loop processing
boolean loopFlg = true;
while(loopFlg) {
Thread.sleep(1000);
System.out.println("In a loop");
}
return a + b + c;
}
}
}
Execution result
In a loop
In a loop
In a loop
In a loop
In a loop
In a loop
In a loop
In a loop
In a loop
In a loop
java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask.get(FutureTask.java:205)
at main.Main.main(Main.java:24)
0
Don't generate an infinite loop
Recommended Posts