"Multithreading" lets a thread return a value

Source: Internet
Author: User
Tags derick

Many times, we use threads to handle some business and want to get results, when we can use callable.

The following example simulates using a thread query db to get a list.

Example

Thread that returns a list data

 Packagecom.nicchagil.study.thread.cnblogs.No02 A thread that can return a value;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.TimeUnit; Public classQuerydatathreadImplementsCallable<list<map<string, object>>> {        Privatemap<string, object> param =NULL;  PublicQuerydatathread (map<string, object>param) {        Super();  This. param =param; } @Override PublicList<map<string, object>> call ()throwsException {/*get result set after simulating query db*/System.out.println ("Param" +param); Map<string, object> map1 =NewHashmap<string, object>(); Map1.put ("id", "1001"); Map1.put ("Name", "Nick Huang."); Map<string, object> map2 =NewHashmap<string, object>(); Map2.put ("id", "1002"); Map2.put ("Name", "Darren Lin"); List<map<string, object>> list =NewArraylist<map<string, object>>();        List.add (MAP1);                List.add (MAP2); /*set a short sleep to see the effect*/        Try{TimeUnit.SECONDS.sleep (3); } Catch(interruptedexception e) {e.printstacktrace (); }                returnlist; }    }
View Code

Starts the thread and waits for the result to be returned

 Packagecom.nicchagil.study.thread.cnblogs.No02 A thread that can return a value;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future; Public classCall { Public Static voidMain (string[] args) {List<map<string, object>> list =NULL; Try{List=query (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }                if(List! =NULL&& list.size () > 0) {             for(Map<string, object>map:list) {System.out.println ("ID:" + map.get ("id") + ", Name:" + map.get ("name"))); }        }    }        /*** Business methods for simulating queries*/     Public Staticlist<map<string, object>> query ()throwsinterruptedexception, executionexception {executorservice es=Executors.newcachedthreadpool (); /*simulating query Parameters*/Map<string, object> param =NewHashmap<string, object>(); Param.put ("username", "Derick"); Future<list<map<string, object>>> future = Es.submit (Newquerydatathread (param)); List<map<string, object>> list =NULL; Try{List=Future.get (); } finally{es.shutdown (); }                returnlist; }}
View Code

More?

Threads that query user data

 Packagecom.nicchagil.study.thread.cnblogs.No02 A thread that can return a value. No002 multiple queries;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.TimeUnit; Public classQuerydatathreadImplementsCallable<list<map<string, object>>> {        Privatemap<string, object> param =NULL;  PublicQuerydatathread (map<string, object>param) {        Super();  This. param =param; } @Override PublicList<map<string, object>> call ()throwsException {/*get result set after simulating query db*/System.out.println ("Query user param" +param); Map<string, object> map1 =NewHashmap<string, object>(); Map1.put ("id", "1001"); Map1.put ("Name", "Nick Huang."); Map<string, object> map2 =NewHashmap<string, object>(); Map2.put ("id", "1002"); Map2.put ("Name", "Darren Lin"); List<map<string, object>> list =NewArraylist<map<string, object>>();        List.add (MAP1);                List.add (MAP2); /*set a short sleep to see the effect*/        Try{TimeUnit.SECONDS.sleep (3); } Catch(interruptedexception e) {e.printstacktrace (); }                returnlist; }    }
View Code

Thread that queries the address data

 Packagecom.nicchagil.study.thread.cnblogs.No02 A thread that can return a value. No002 multiple queries;ImportJava.util.HashMap;ImportJava.util.Map;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.TimeUnit; Public classQueryextdatathreadImplementsCallable<map<string, object>> {        Privatemap<string, object> param =NULL;  PublicQueryextdatathread (map<string, object>param) {        Super();  This. param =param; } @Override PublicMap<string, object> call ()throwsException {/*get result set after simulating query db*/System.out.println ("Query address param" +param); Map<string, object> map =NewHashmap<string, object>(); Map.put ("1001", "Hz"); Map.put ("1002", "PL"); /*set a short sleep to see the effect*/        Try{TimeUnit.SECONDS.sleep (3); } Catch(interruptedexception e) {e.printstacktrace (); }                returnmap; }    }
View Code

Calls the thread that queries the user data and address data concurrently, merges the data, and returns

 Packagecom.nicchagil.study.thread.cnblogs.No02 A thread that can return a value. No002 multiple queries;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future; Public classCall { Public Static voidMain (string[] args) {List<map<string, object>> list =NULL; Try{List=query (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }                if(List! =NULL&& list.size () > 0) {             for(Map<string, object>map:list)            {System.out.println (map); }        }    }        /*** Business methods for simulating queries*/     Public Staticlist<map<string, object>> query ()throwsinterruptedexception, executionexception {executorservice es=Executors.newcachedthreadpool (); /*simulating query Parameters*/Map<string, object> param =NewHashmap<string, object>(); Param.put ("username", "Derick"); Future<list<map<string, object>>> userfuture = Es.submit (Newquerydatathread (param)); Future<map<string, object>> addressfuture = Es.submit (Newqueryextdatathread (param)); List<map<string, object>> userlist =NULL; Map<string, object> addressmap =NULL; Try{userlist=Userfuture.get (); Addressmap=Addressfuture.get (); } finally{es.shutdown (); }                /*Merging Business Data*/        if(UserList! =NULL&& userlist.size () > 0) {             for(Map<string, object>map:userlist) {Map.put ("Address", Addressmap.get (Map.get ("id")))); }        }                returnuserlist; }}
View Code

Reference API

Callable<v>

Future<v>

Executorservice.submit (java.util.concurrent.Callable)

Interruptedexception

Executionexception

"Multithreading" lets a thread return a value

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.