Written in front: the main content for Huang teacher video sharing lessons of the study notes.
1) Why do I need multi-threading?
-
Resolve time-consuming tasks
File IO, networking requests, database operations, RPC
-
Increase concurrency capabilities
Handle more things at the same time
-
Prevent ANR
Inputdispatching Timeout: Input event distribution Timeout 5s (touch or key)
Service Timeout: not done within 20s
Broadcastqueue Timeout: The foreground broadcast is not finished in 10s
ContentProvider Timeout: Content provider execution timeout
-
Avoid dropping frames
To reach 60 frames per second, each frame must be 16ms processed
2) Use several types of multi-threaded poses
- Thread
①new Thread, overloaded Run method;
② implements the Runable interface, which is passed as a parameter to thread.
Public Static void Main(string[] args) {the ID of the UI thread in//android is constant 1System. out. println ("UI Thread Id:"+thread.currentthread (). GetId ());NewThread () {@Override Public void Run() {//TODO:2016/12/2System. out. println ("Run in thread"+thread.currentthread (). GetId ()); }}.start (); Runnable Runnable =NewRunnable () {@Override Public void Run() {//TODO:2016/12/2System. out. println ("Run in thread"+thread.currentthread (). GetId ()); } };NewThread (runnable). Start (); }
An Android-specific lightweight asynchronous task class that can perform background tasks in a thread pool and then pass the execution progress and results to the main thread to update the UI. But it is not suitable for particularly time-consuming background tasks.
(Android-specific, for ease of updating the UI, launched by Google)
Public classMyTask extends asynctask<string,integer,string> {String TAG ="haha"; @Overrideprotected void OnPreExecute() {//TODO:2016/12/2LOG.D (TAG,"OnPreExecute run in Thread"+thread.currentthread (). GetId ()); }//Only This method executes in the background, and the other methods are in the UI thread@OverrideprotectedStringDoinbackground(String ...params) {//TODO:2016/12/2LOG.D (TAG,"Doinbackground run in Thread"+thread.currentthread (). GetId ());the parameters passed in are the same as those passed in executeLOG.D (TAG,"Input param"+params[0]);//This method uses callback Onprogressupdate for progress updatesPublishprogress (5);//This return information will be passed to OnPostExecute return "Task done!"; } @Overrideprotected void onprogressupdate(Integer ... values) {//TODO:2016/12/2LOG.D (TAG,"onprogressupdate run in Thread"+thread.currentthread (). GetId ()); LOG.D (TAG,"Update Progress"+values[0]); } @Overrideprotected void OnPostExecute(String s) {//TODO:2016/12/2LOG.D (TAG,"OnPostExecute run in Thread"+thread.currentthread (). GetId ()); LOG.D (TAG,"OnPostExecute input"+s); }}
Analysis: Asynctask only Doinbackground executes in child threads, others are in the UI thread.
Use note points:
1) Imagine a situation: on an Activity page, if the Asynctask task is initiated and then the page is left/destroyed, what is the problem if Doinbackground is not finished?
First of all, Asynctask wasted resources, the results have not been used, because the UI is not;
2) So how to gracefully terminate the Asynctask?
In view of the above problems, we generally want to cancel the Asynctask task when the activity ondestory.
3) about the Cancel () method
The Cancel () method does not directly stop the asynctask background thread, but instead sends a stop thread's status bit,
It is therefore necessary to constantly check this status bit in Doinbackground.
such as: if (iscancelled ()) return null; The task is canceled, exit immediately.
Handlerthread is actually a thread with a looper that can deliver messages to child threads.
@Override protected void onCreate(@Nullable Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//handlerthread is actually a thread with Looper.Handlerthread Handlerthread =NewHandlerthread ("Handler-thread"); Handlerthread.start (); LOG.D (TAG,"Handlerthread ID:"+handlerthread.getid ());//Use handlerthread Looper to generate handler for sending messages to child threads, runnable, etc.Handler Handler =NewHandler (Handlerthread.getlooper ()) {@Override Public void Handlemessage(Message msg) {LOG.D (TAG,"Handlemessage received in thread"+thread.currentthread (). GetId ()); LOG.D (TAG,"received message is"+msg.obj); } };//Must start thread firstRunnable Runnable =NewRunnable () {@Override Public void Run() {LOG.D (TAG,"This runnable run in thread"+thread.currentthread (). GetId ()); } };//Make runnable on child threads (that is, handlerthread thread execution)Handler.post (runnable);//This message is sent to the Handlerthread threadMessage message =NewMessage (); Message.obj ="test Message"; Handler.sendmessage (message); }
First, take a look at several important classes and interfaces for concurrent programming under the Java.util.concurrent package: Executor,executors, Executorservice.
Executor (Actuator):
Below, is an interface that provides the execute () method to perform a task without explicitly creating a thread (using its internal thread pool to complete the operation).
Its most commonly used sub-interface, Executorservice, extends the shutdown (), submit (), and other methods for managing termination tasks.
Executorservice:
Shutdown: After the submitted task has been completed (no new tasks can be submitted after the call, and wait for the submitted task to finish), close executorservice to reclaim the resources.
Submit: Returns the future object for canceling execution or waiting for completion.
InvokeAll: for batch execution.
Executors:
Primarily used to provide thread pool-related operations and return executor actuators.
Then look at several different thread pools: Fixedthreadpool, Cachedthreadpool, Scheduledthreadpool, Singlethreadpool.
Fixedthreadpool:
Created by Executors.newfixedthreadpool (), is a thread pool with a fixed number of threads. Threads are not recycled unless the thread pool is closed. When all threads are active, new tasks are blocked until a thread is available.
Suitable for fixed thread count.
Cachedthreadpool:
Created by Executors.newcachedthreadpool (), the number of threads is variable. Only non-core threads, the maximum number of threads is integer.max_value.
Idle threads have a time-out mechanism that is 60s long and more than 60s of idle threads are recycled.
When there is no idle thread, a new thread is created for the new task, guaranteeing that all tasks are immediately executed.
Suitable for performing a large and time-consuming task, the number of threads is created on demand and the collection is exhausted.
Runnable runnable2 = new Runnable () {@Override public void run () {Log. D(TAG,"Runnable2 run in Thread"+thread. CurrentThread(). GetId());try {Timeunit. SECONDS. Sleep(2);} catch (Interruptedexception e) {E. Printstacktrace();Log. D(TAG,"Runnable2 is interrupted");} Log. D(TAG,"Mission Accomplished!" ");} };Executorservice Executorservice = Executors. Newcachedthreadpool();Executorservice. Execute(Runnable2);Executorservice. Execute(Runnable2);try {//HibernateTenThe tasks in front of s are all done and the threads are not recycled, and the newly added task will use the existing idle thread timeunit. SECONDS. Sleep(Ten);} catch (Interruptedexception e) {E. Printstacktrace();}//Will re-use the previous two idle threads Executorservice. Execute(Runnable2);Executorservice. Execute(Runnable2);try {//Hibernate -s idle thread is recycled and the newly added task will start a new thread timeunit. SECONDS. Sleep( -);} catch (Interruptedexception e) {E. Printstacktrace();}//All idle threads are idle -S and is recycled thus the newly added task will create a new thread Executorservice. Execute(Runnable2);Executorservice. Shutdown();
Scheduledthreadpool:
Created by Executors.newscheduledthreadpool (), the number of cores is fixed and the number of non-core threads is unlimited, and is reclaimed immediately when non-core threads are idle.
Suitable for repetitive tasks with timed and fixed cycles.
Runnable runnable2 = new Runnable () {@Override public void run () {Log. D(TAG,"Runnable2 run in Thread"+thread. CurrentThread(). GetId());try {//Sleep1Min to facilitate the observation of the results timeunit. SECONDS. Sleep( -);} catch (Interruptedexception e) {E. Printstacktrace();Log. D(TAG,"Runnable2 is interrupted");} Log. D(TAG,"Mission Accomplished!" ");} };Scheduledexecutorservice Scheduledexecutorservice = Executors. Newscheduledthreadpool(2);Scheduledexecutorservice. Schedule(Runnable2,1, Timeunit. SECONDS);Scheduledexecutorservice. Schedule(Runnable2,1, Timeunit. SECONDS);When created, the number of core threads is2So the number of tasks is greater than2Waits for the previous task to finish before it starts to execute the new task Scheduledexecutorservice. Schedule(Runnable2,1, Timeunit. SECONDS);Scheduledexecutorservice. Shutdown();
(Note the time and thread ID of the task completion)
Singlethreadpool:
Created by Executors.newsinglethreadexecutor (), there is only one core thread, so all tasks are executed sequentially, so there is no need to handle thread synchronization issues.
Runnable Runnable1 =NewRunnable () {@Override Public void Run() {LOG.D (TAG,"Runnable1 run in Thread"+thread.currentthread (). GetId ()); } }; Runnable Runnable2 =NewRunnable () {@Override Public void Run() {LOG.D (TAG,"Runnable2 run in Thread"+thread.currentthread (). GetId ());Try{TimeUnit.SECONDS.sleep (1); }Catch(Interruptedexception e) {E.printstacktrace (); LOG.D (TAG,"Runnable2 is interrupted"); } } }; Executorservice Singlethreadtool = Executors.newsinglethreadexecutor (); Singlethreadtool.execute (RUNNABLE1); Singlethreadtool.execute (RUNNABLE1); Future future = Singlethreadtool.submit (Runnable2);Try{TimeUnit.MILLISECONDS.sleep ( -); }Catch(Interruptedexception e) {E.printstacktrace (); }//Stop Runnable2Future.cancel (true);//close thread poolSinglethreadtool.shutdown ();//This task will not be executedSinglethreadtool.submit (RUNNABLE1);
Intentservice is a special service that inherits from the service and is an abstract class. Its subclasses must implement the Onhandleintent method.
Intentservice the bottom layer is realized by Handlerthread. The Onhandleintent method runs in the background.
Because Intentservice is a service that is not easily killed by the system, it is suitable for performing high-priority background tasks.
3) Common issues with multithreading
- Life cycle
Long running time, not subject to UI lifecycle restrictions, referencing external UI classes, activity is prone to memory leaks.
- UI actions
- The UI is usually not directly operational and needs to be matched with handler.
- Thread Synchronization Issues
4) Applicable scenarios
- Thread
The default priority is the same as the thread that was created, suitable for a single time-consuming task, and ends up executing itself.
-
Handlerthread
The default priority is Chengtong with the UI line, and using too much will cause the UI to get stuck;
You need to call Handlerthread.quit () to exit manually when not in use.
-
Asynctask
The essence is the encapsulation of Threadpoolexecutor and Futuretask, which defaults to the background thread priority.
Provides the ability to cancel, progress notifications, and modify the UI, but is not easy to use.
An exception is thrown when the number of creation is more than 128.
Compatibility: 1.6 To 2.x concurrent execution, 3.0 serial execution. First use before 4.1 must be created on the UI thread.
-
Executorservice
Priority is the default priority, and calls to the shutdown recycle thread pool when not in use.
-
Intentservice
Does not depend on the UI, is suitable for the background operation, executes the task automatically exits.
5) Recommended multi-threaded usage
-
Common scenario, requiring high concurrency
Executors.newfixedthreadpool () High multiplexing
Executors.newcachedthreadpool () Low Latency
-
Sequential execution required
Using Handlerthread
- Background execution required
Intentservice
Various poses for multi-threaded use in Android