
In this post I will demonstrate a way to achieved that based on Callable and Executors.
The Callable Interface is very similar to Runnable, here is an implementation example :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.Callable; | |
public class MyTask implements Callable<Integer> { | |
private int numerator; | |
private int denominator; | |
public MyTask(int n, int d) { | |
this.numerator = n; | |
this.denominator = d; | |
} | |
@Override | |
//The call method may throw an exception | |
public Integer call() throws Exception { | |
if (denominator == 0) | |
throw new Exception("cannot devide by zero"); | |
else | |
return numerator/denominator; | |
} | |
} |
Here is an example :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
public class Main { | |
public static void main(String[] args) { | |
//Build a task and an executor | |
MyTask task = new MyTask(2, 0); | |
ExecutorService threadExecutor = Executors.newSingleThreadExecutor(); | |
try { | |
//Compute the task in a separate thread | |
int result = (int) threadExecutor.submit(task).get(); | |
System.out.println("The result is " + result); | |
} | |
catch (ExecutionException e) { | |
//Handle the exception thrown by the child thread | |
if (e.getMessage().contains("cannot devide by zero")) | |
System.out.println("error in child thread caused by zero division"); | |
} | |
catch (InterruptedException e) { | |
//This exception is thrown if the child thread is interrupted. | |
e.printStackTrace(); | |
} | |
} | |
} |
In that case main thread never done all task before created thread execution finished.
ReplyDelete