Java Threads (vii): Callable and future

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/ghsau/article/details/7451464


This article describes the callable and the future, they are very interesting, one produces results, one to get results.
Callable interface is similar to runnable, can be seen from the name, but Runnable will not return results, and can not be thrown to return the result of the exception, and callable more powerful, after being executed by the thread can return a value, this return value can be obtained by the future , that is to say, the future can get the return value of the asynchronous execution task, here is a simple example:

public class Callableandfuture {
public static void Main (string[] args) {
callable<integer> callable = new callable<integer> () {
Public Integer Call () throws Exception {
return new Random (). Nextint (100);
}
};
futuretask<integer> future = new futuretask<integer> (callable);
New Thread (Future). Start ();
try {
Thread.Sleep (5000);//may do something
System.out.println (Future.get ());
} catch (Interruptedexception e) {
E.printstacktrace ();
} catch (Executionexception e) {
E.printstacktrace ();
}
}
}

Futuretask implements two interfaces, runnable and future, so it can be executed as a runnable thread, and can be used as the future to get callable return value, so what is the benefit of using this combination? Assuming that there is a time-consuming return value that needs to be computed, and that the return value is not immediately required, then you can use this combination to compute the return value with another thread, and the current thread can do other things before using the return value, and when this return value is needed, then the future is not beautiful! Here is an introduction to the future model: Http://openhome.cc/Gossip/DesignPattern/FuturePattern.htm.
Here's another way to use callable and the future, execute callable through the Executorservice submit method, and return to the future with the following code:

public class Callableandfuture {
public static void Main (string[] args) {
Executorservice ThreadPool = Executors.newsinglethreadexecutor ();
future<integer> future = Threadpool.submit (new callable<integer> () {
Public Integer Call () throws Exception {
return new Random (). Nextint (100);
}
});
try {
Thread.Sleep (5000);//may do something
System.out.println (Future.get ());
} catch (Interruptedexception e) {
E.printstacktrace ();
} catch (Executionexception e) {
E.printstacktrace ();
}
}
}

The code is not a lot simpler, Executorservice inherits from executor, its purpose is to manage thread objects for us, thus simplifying concurrent programming, executor we do not need to display to manage the life cycle of threads, is the preferred way to launch tasks after JDK 5.
Execute multiple tasks with return values and get multiple return values, with the following code:

public class Callableandfuture {
public static void Main (string[] args) {
Executorservice ThreadPool = Executors.newcachedthreadpool ();
Completionservice<integer> cs = new executorcompletionservice<integer> (ThreadPool);
for (int i = 1; i < 5; i++) {
final int taskID = i;
Cs.submit (New callable<integer> () {
Public Integer Call () throws Exception {
return TaskID;
}
});
}
Might do something
for (int i = 1; i < 5; i++) {
try {
System.out.println (Cs.take (). get ());
} catch (Interruptedexception e) {
E.printstacktrace ();
} catch (Executionexception e) {
E.printstacktrace ();
}
}
}
}

In fact, you can not use Completionservice, you can first create a set of future types, with executor submitted task return value added to the collection, and finally iterate through the collection of data, code slightly. Updated in 2016-02-05, the comment on this argument triggered a discussion, in fact, I did not clear, sorry. Here again: the future submitted to Completionservice is arranged in the order of completion, in which the future is arranged in the order in which it is added. So the difference between the two approaches is as Fishjam in the commentary.

Java Threads (vii): Callable and future

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.