Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

Thread

執行緒,和執行緒以外的。

Background Tasks

ref

  • 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
2
3
4
5
6
7
new Thread(new Runnable() {
@Override
public void run(){
// accessing data from database or creating network call
Toast.makeText(this, "Task is Completed.", Toast.LENGTH_SHORT).show();
}
}).start();

Handler

  • For scheduling tasks.
  • To communicate between threads.
  • Often used in update UI thread from an long-running operation from a background thread.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run(){

handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(this, "Task is Completed.", Toast.LENGTH_SHORT).show();
}
});
}
}).start();

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
private class DownloadTask extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... urls) {
// Perform the background task, such as downloading data from a server
String result = "";
try {
URL url = new URL(urls[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
result = readStream(in);
urlConnection.disconnect();
} catch (Exception e) {
Log.e("DownloadTask", e.getMessage());
}
return result;
}

@Override
protected void onPostExecute(String result) {
// Update the UI with the result of the background task
textView.setText(result);
}

private String readStream(InputStream is) {
// Helper method to read an InputStream into a String
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}

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.

  1. If there is a time-consuming operation, use asynctask instead.
  2. 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.

  1. Use Memory Profiler or LeakCanary to monitor memory leaks.
  2. Reduce memory consumption and use lightweight data structures. For example, use SparseArray instead of HashMap, use ArrayList instead of LinkedList, etc.
  3. Compress large images
  4. Algorithm optimization (binary search replaces linear search).

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels