執行緒,和執行緒以外的。
Background Tasks
- Execute immediately: Background thread
If we didn’t use thread, run a long-running task on UI thread, it will cause ANR(Application Not Responding) for 5 seconds, UI thread should focus on UI, we can update the UI in the UI thread using a Handler or AsyncTask.
Thread
- Lowest level of the three.
Long-running operations
( Network requests…).- Runs on background, not affect the UI thread.
- Careful synchronization and concurrency issues(race condition), use synchronized or ReentrantLock keyword.
- Variables with ThreadLocal keyword ensure it only visible in current thread.
1 | new Thread(new Runnable() { |
Handler
- For scheduling tasks.
- To communicate between threads.
- Often used in
update UI thread
from an long-running operation from a background thread.
1 | final Handler handler = new Handler(); |
Methods
post()
Allows us to execute code on a specific thread without having to create a new thread explicitly.sendMessage(Message msg)
Sends a Message object to the Handler’s message queue.sendEmptyMessage(int what)
postDelayed(Runnable r, long delayMillis)
Posts a Runnable object to the Handler’s message queue after a specified delay.removeMessages(int what)
Removes any pending messages with a specific what value.removeCallbacks(Runnable r)
It removes with a callback.
AsyncTask
- Higher-level abstraction, internally uses a Handler and a Thread to execute the task.
Short-lived tasks
( Downloading a file…).- It runs on a separate thread, but no needs to create a new thread, automatically updates the UI thread when the task completes.
- Not require much communication between different components.
1 | private class DownloadTask extends AsyncTask<String, Void, String> { |
Methods
onPreExecute()
Main thread.doInBackground()
Async thread, executing the long-running task.onProgressUpdate()
Main thread, Update the UI while doInBackground() working.onPostExecute()
Main thread.
Task
Asynchronous operation that can be executed in the background.
Sleep and Wait
Both used to pause the execution of a thread for a specific amount of time.
Sleep()
Single thread.Wait()
Multi-thread, use locker, wake up by notify.
Deadlock
Two thread waiting for eachother, causing the program to hang or crash.
ANR(Application Not Responding)
App on UI thread does not respond for more than 5 seconds.
- If there is a time-consuming operation, use asynctask instead.
- Check for deadlock or infinite loop, use Memory Profiler or LeakCanary to monitor memory leaks.
- User interact: less than 0.2s
- Start App: less than 0.5s
OOM(Out of Memory)
There is not enough memory for the program to run.
- Use Memory Profiler or LeakCanary to monitor memory leaks.
- Reduce memory consumption and use lightweight data structures. For example, use SparseArray instead of HashMap, use ArrayList instead of LinkedList, etc.
- Compress large images
- Algorithm optimization (binary search replaces linear search).
如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)