http://icgemu.iteye.com/blog/467848
Use of return values in Java threads
Blog Category:
Javathread sometimes requires a value in the thread to be returned in the threads, and in general we will use the Runnable interface and the thread class to set a variable, change the value of the variable in run (), and use a Get method to get the value, but when the run finishes is unknown ; We need some mechanism to ensure that.
In Java SE5 There is a callable interface, we can use this interface to complete the function;
Code such as:
Java code
- Package com.threads.test;
- Import java.util.concurrent.Callable;
- Public class Callablethread implements callable<string> {
- private String str;
- private int count=10;
- Public callablethread (String str) {
- This.str=str;
- }
- //need to implement the call method for callable
- Public String Call () throws Exception {
- For (int i=0;i<this.count;i++) {
- System.out.println (this.str+"" +i);
- }
- return this.str;
- }
- }
Executing the same task in the call method as in the run () method, unlike call (), which has a return value.
The return type of call should be the same as the generic type of callable<t>.
The test code is as follows:
Java code
- Package com.threads.test;
- Import java.util.ArrayList;
- Import java.util.concurrent.ExecutionException;
- Import Java.util.concurrent.ExecutorService;
- Import java.util.concurrent.Executors;
- Import Java.util.concurrent.Future;
- Public class Callabletest {
- public static void Main (string[] args) {
- Executorservice Exs=executors.newcachedthreadpool ();
- arraylist<future<string>> al=New arraylist<future<string>> ();
- For (int i=0;i<10;i++) {
- Al.add (Exs.submit (new Callablethread ("String" +i));
- }
- For (future<string> fs:al) {
- try {
- System.out.println (Fs.get ());
- } catch (Interruptedexception e) {
- E.printstacktrace ();
- } catch (Executionexception e) {
- E.printstacktrace ();
- }
- }
- }
- }
The Submit () method returns a Futrue object that can be returned by calling the Get method of the object.
This method can be used to handle the problem of the return value in the thread very well.
- Callable.jar (3.9 KB)
- Download number of times: 91
Use of return values in Java threads