In section 1, we use handler, thread/runnable, URL, httpurlconnection, and so on to asynchronously download network images. Then the asynctask method is changed in section 2. Then we will apply other methods in this Section. This method is a bit similar to the first section. I feel like I have taken a circle back to the original place, but the scenery is more beautiful. This is often the case in life, from null to null.
Who is it? Java. util. Concurrent
Java. util. Concurrent is a common Utility Class in concurrent programming.
Executorservice class: executors with a service life cycle.
Executors class: Executor, which will manage the thread object for you.
We know that these are used to process concurrent tasks. Of course, our demo only requests an image and cannot reflect concurrency, but suppose we have a listview, what if a network image is required for each item? Then concurrency can be reflected: multiple threads concurrently download images from the network. Of course, this version does not use listview to display multiple items. Make a version later! Under research.
The idea is as follows:
1: dynamically create n threads to prevent them from being in the thread pool.
2: The system extracts a thread from the thread pool for execution. If no thread is available in the thread pool, other tasks are called only after they are waited until a new thread is released.
There are several ways to dynamically specify the number of threads.
Newfixedthreadpool (INT nthreads) specifies the number of threads
The newcachedthreadpool () system creates a thread for each task.
The following code downloads data concurrently:
View code
Case R. Id. btnthress:
Progress. setvisibility (view. Visible );
Final Handler newhandler = New Handler ();
Executorservice. Submit ( New Runnable (){
@ Override
Public Void Run (){
Try {
URL newurl = New URL (Params );
Httpurlconnection Conn = (Httpurlconnection) newurl. openconnection ();
Conn. setdoinput ( True );
Conn. Connect ();
Inputstream = Conn. getinputstream ();
Bitmap = Bitmapfactory. decodestream (inputstream );
Newhandler. Post ( New Runnable (){
@ Override
Public Void Run (){
Imageview View = (Imageview) framelayout. findviewbyid (R. Id. Image );
View. setimagebitmap (Bitmap );
}
});
} Catch (Malformedurlexception e ){
E. printstacktrace ();
} Catch (Ioexception e ){
E. printstacktrace ();
}
}
});
Break ;
The running result is: