Java Tutorial Source Code: The Callable Interface
public void run()
The drawbacks in creating threads this way are:
- The run method cannot return a result since it has void as its return type.
- Second, the run method requires you to handle checked exceptions within this method since the overriden method does not use any throws clause.
public MyRunnable implements Runnable {
private int result = 0;
public void run() {
...
result = someValue;
}
/* The result attribute is protected from changes from other
codes accessing this class */
public int getResult() {
return result;
}
}
Java Tutorial Source Code: The Callable Interface
With the Callable interface, getting the result is simple as shown in the next example.
import java.util.concurrent.*;
public class MyCallable implements Callable {
public Integer call() throws java.io.IOException {
...
return someValue;
}
}
The call method has the following signature:
V call throws Exception
V here is a generic type, which means that the return type of call can be of any reference type. You will learn more about generic types in a latter chapter.
There are still more concurrency features in J2SE5.0. Please refer to the API documentation for a detailed discussion of these other features.
No comments:
Post a Comment