Connect to the above
legacy Issues in the previous article
For Java multithreading, 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. However, once a deadlock is involved and access to shared resources and the status and execution order and thread return values of the threads are monitored at any time.
Introduction to Callable and future
The callable interface represents a piece of code that can be called and returns the result; The future interface represents information such as the state, return value, and so on when the asynchronous task is executed. So callable is used to produce results, and the future is used to get results.
1. Callable
Callable is an interface that contains only 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 of 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 get the results of the calculation.
Future source code is as follows:
<span style= "FONT-SIZE:18PX;" >public interface Future<v> { //attempted to cancel execution of this task. Boolean Cancel (boolean mayinterruptifrunning)//Returns True if it is canceled before the task is completed properly. boolean iscancelled ()//Returns True if the task is completed. boolean IsDone ()//If necessary, wait for the calculation to complete and then get its results. V Get () throws interruptedexception,executionexception;//, if necessary, waits for the result to be obtained after the calculation is completed for a given time (if the result is available). V Get (long timeout, timeunitunit) throws Interruptedexception,executionexception, TimeoutException;} </span>
basic usage of callable and future of the example
Let's start with an example to see the basic usage 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; Perform 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 (); Perform tasks and get future objects Future F1 = Pool.submit (c1); Output result System.out.println (F1.get ()); Close the thread pool Pool.shutdown (); }}</span>
Operation result :
4950
Result Description :
In main thread main, create a new thread pool through Newsinglethreadexecutor (). The callable object C1 is then created, and then the C1 is submitted to the thread pool through Pool.submit (c1) for processing, and the returned results are saved 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 possible to modify the thread code implemented by 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 (); Simple to determine whether the user entered the mobile phone number (segment) is legal if ("". Equals (phonesec) | | Phonesec.length () < 7) {//Give error Phonesecedittext.seterror ("You entered the mobile number (segment) is wrong! "); 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 a thread from callable and future, call webservice//to create a task with a return value callablethread callable = Newcallablethread (Namespace,metho Dname,endpoint,soapaction,params,vals); Create a thread pool Executorserviceexecutor=executors.newcachedthreadpool (); Perform 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 calls () throws exception{//The implementation of this method is shown in the previous article or the source return Getremoteinfo (Namespace,methodname, EndPoint, Soapaction,params,vals); }} </span>
At this point, the Android call WebService is perfect to complete.
Source Download
http://download.csdn.net/detail/tcl_6666/7365341