Threads with return values in Java threads callable

Source: Internet
Author: User

Before Java5, threads are not return values, often for "have" return value, a lot of trouble, and the code is very difficult to write. Or just go around the ridge and take the other way. Now Java finally has a task that can return a value (also called a thread).

A task that can return a value must implement the callable interface, and similarly, a task that has no return value must runnable the interface.

After performing the callable task, you can get a future object that is called get on the object to get to the object returned by the callable task.

Here is a very simple example:

Package COM.LYC

Import java.util.concurrent.Callable;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;


public class Callablefuturetest {


public static void Main (string[] args) throws Executionexception, Interruptedexception {
Callablefuturetest test = new Callablefuturetest ();

Create a pool of threads
Executorservice pool = Executors.newfixedthreadpool (2);
Create two tasks with a return value
Callable C1 = Test.new mycallable ("A");
Callable C2 = Test.new mycallable ("B");

Perform tasks and get future objects
Future F1 = Pool.submit (c1);
Future F2 = Pool.submit (C2);

Gets the return value of the task from the future object and outputs it to the console
SYSTEM.OUT.PRINTLN ("----" + f1.get (). toString ());
SYSTEM.OUT.PRINTLN ("----" + f2.get (). toString ());

Close the thread pool
Pool.shutdown ();
}

Class Mycallable implements callable {
Private String oid;

Mycallable (String oid) {
This.oid = oid;
}

Public Object Call () throws Exception {
Return OID + "content returned by task";
}
}
}

Threads with return values in Java threads callable

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.