Connect to the above
legacy Issues in the previous article
For Java Multi-threading understanding. I used to confine myself to implementing the Runnable interface or inheriting the thread class, then overriding the run () method, and finally the start () call was done. However, once a deadlock is involved and access to a shared resource is monitored and the thread's state and run order and thread return values are kept up-to-date.
Brief introduction of callable and future
The callable interface represents a section of code that can invoke and return results; The future interface represents information such as the state, return value, and so on when the asynchronous task is run. So callable is used to produce results, and the future is used to get results.
1. Callable
Callable is an interface that only includes a call () method. Callable is a task that returns results and can throw exceptions.
For the sake of understanding, we can compare callable to a runnable interface, and callable's call () method is similar to the runnable run () method.
The source code for callable is as follows:
<span style= "FONT-SIZE:18PX;" >publi cinterface callable<v> { V call () throws Exception;} </span>
2. Future
The future is an interface. It is used to represent the result of an asynchronous calculation. Provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to obtain the result of the calculation.
The source code for the future is as follows:
<span style= "FONT-SIZE:18PX;" >public interface Future<v> { //attempted to cancel the operation of this task. Boolean Cancel (boolean mayinterruptifrunning)//assumes True if the task is canceled before it is properly completed. boolean iscancelled ()//Returns True if the task is finished. boolean IsDone ()//If necessary, wait for the calculation to complete and then get its result. V Get () throws interruptedexception,executionexception;//, if necessary, waits for the result to be obtained (assuming the result is available) after the time given for the calculation to be completed. V Get (long timeout, timeunitunit) throws Interruptedexception,executionexception, TimeoutException;} </span>
demonstrates the basic use of callable and future of the sample
Let's start with a demo sample to see the basic use of callable and future
<span style= "FONT-SIZE:18PX;" >importjava.util.concurrent.callable;importjava.util.concurrent.future;importjava.util.concurrent.executors ; importjava.util.concurrent.executorservice;importjava.util.concurrent.executionexception; Classmycallable implements callable {@Override public Integer call () throws Exception {int sum = 0; Run task for (int i=0; i<100; i++) sum + = i; return sum; return integer.valueof (sum); }} publicclass CallableTest1 {public static void main (string[] args) throws Executionexception,interruptedexce ption{//Create a thread pool Executorservice pool =executors.newsinglethreadexecutor (); Create a task with a return value callable C1 = new mycallable (); Run the task and get the future object Future F1 = Pool.submit (c1); Output result System.out.println (F1.get ()); Close the thread pool Pool.shutdown (); }}</span>
Execution Result :
4950
Result Description :
In main thread main, create a new thread pool through Newsinglethreadexecutor (). Next, create the callable object C1. The C1 is then submitted to the thread pool for processing by Pool.submit (C1). and save the returned results to the future object F1.
We then get the saved results from the callable through F1.get () and finally close the thread pool through Pool.shutdown ().
back to topic: Call to query the webservice of the cell phone number attribution
in fact, through the simple example above, it is entirely possible to change the thread code implemented through the Runnable interface or the thread class into callable and Future the implemented thread.
<span style= "FONT-SIZE:18PX;" >public class Main activity extends activity {public static final String TAG = "WEBSERVICE_PJ"; Private EditText Phonesecedittext; Private TextView Resultview; Private Button Querybutton; @Override public void OnCreate (bundlesavedinstancestate) {//Strictmode.setthreadpolicy (newstric TMode.ThreadPolicy.Builder ()//. Detectdiskreads (). Detectdiskwrites (). Detectnetwork ()//. Penaltylog (). Build ()) ;////Strictmode.setvmpolicy (NewStrictMode.VmPolicy.Builder ()//. Detectleakedsqlliteobjects (). penaltyl OG (). Penaltydeath ()//. Build ()); Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Phonesecedittext = (EditText) Findviewbyid (R.ID.PHONE_SEC); Resultview = (TextView) Findviewbyid (R.id.result_text); Querybutton = (Button) Findviewbyid (R.ID.QUERY_BTN); Querybutton.setonclicklistener (Newonclicklistener () { @Override public void OnClick (View v) {log.i (TAG, "Mainactivity thread ID:" +t Hread.currentthread (). GetId ()); Mobile number (segment) String phonesec =phonesecedittext.gettext (). toString (). Trim (); Simply infer whether the mobile number (segment) entered by the user is legal if ("". Equals (phonesec) | | Phonesec.length () < 7) {//Give error Phonesecedittext.seterror ("The mobile number (segment) you entered is incorrect. "); Phonesecedittext.requestfocus (); The TextView that displays the results of the query is emptied Resultview.settext (""); Return }//namespace String nameSpace = "http://WebXml.com.cn/"; The method name called String methodName = "Getmobilecodeinfo"; EndPoint String EndPoint = "Http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"; SOAP Action String soapaction = "Http://WebXml.com.cn/getMobileCodeInfo"; Method params and Values arraylist<string> params= new arraylist<string> (); Arraylist<object> vals =new arraylist<object> (); Params.add ("Mobilecode"); Params.add ("UserId"); Vals.add (PHONESEC); Vals.add (""); Create threads from callable and future. Call webservice//to create a task with a return value callablethread callable = Newcallablethread (namespace,methodname,endpoint,soapactio N,params,vals); Create a thread pool Executorserviceexecutor=executors.newcachedthreadpool (); Run the task and get the Future object future<string>future = Executor.submit (callable); try {//output result Resultview.settext (Future.get ()); Close the thread pool Executor.shutdown ();} catch (Interruptedexception e) {e.printstacktrace ();} CaTCH (executionexception e) {e.printstacktrace ();} } }); } private class Callablethread implementscallable<string> {private String nameSpace; Private String MethodName; Private String EndPoint; Private String SOAPAction; Private arraylist<string> params; Private arraylist<object> Vals; Public Callablethread (Stringnamespace, String methodName, Stringendpoint, string soapaction, Arrayl Ist<string> params,arraylist<object> vals) {this.namespace = NameSpace; This.methodname = MethodName; This.endpoint = EndPoint; This.soapaction = SOAPAction; This.params = params; This.vals = Vals; }//need to implement callable's call method public String call () throws exception{//The implementation of this method is shown in the previous article or the source code return Getremoteinfo (Namespace,methodname, EndPoint, Soapaction,params,vals); }} </span>
At this point, Android call WebService is complete.
Source code Download
http://download.csdn.net/detail/tcl_6666/7365341
Android platform invoke Web Service: Thread return value