Java Reference
In-Depth Information
Task #1 - Iteration #1 is going to sleep for 9 seconds.
Task #2 - Iteration #1 is going to sleep for 2 seconds.
Task #3 - Iteration #1 is going to sleep for 7 seconds.
Task #2 - Iteration #2 is going to sleep for 5 seconds.
Task #2 - Iteration #3 is going to sleep for 7 seconds.
Task #3 - Iteration #2 is going to sleep for 2 seconds.
...
Result-Bearing Tasks
How do you get the result of a task when it is complete? The task that can return a result upon its execution has to be
represented as an instance of the
Callable<V>
interface. The type parameter
V
is type of the result of the task. Note
that the
run()
method of the
Runnable
interface cannot return a value and it cannot throw any checked exception.
The
Callable
interface has a
call()
method. It can return a value of any type. It allows you to throw an exception. It is
declared as follows:
public interface Callable<V> {
V call() throws Exception;
}
Let's redo your
RunnableTask
class from Listing 6-47 as
CallableTask
, which is shown in Listing 6-49.
Listing 6-49.
A Callable Task
// CallableTask.java
package com.jdojo.threads;
import java.util.Random;
import java.util.concurrent.Callable;
public class CallableTask implements Callable<Integer> {
private int taskId;
private int loopCounter;
private Random random = new Random();
public CallableTask(int taskId, int loopCounter) {
this.taskId = taskId;
this.loopCounter = loopCounter;
}
public Integer call() throws InterruptedException {
int totalSleepTime = 0 ;
for (int i = 1; i <= loopCounter; i++) {
try {
int sleepTime = random.nextInt(10) + 1;
System.out.println("Task #" + this.taskId +
" - Iteration #" + i +
" is going to sleep for " +
sleepTime + " seconds.");