On Android multi-threaded programming

Source: Internet
Author: User
Tags java se

Multithreading in Android is actually multi-threading in Java SE, just for ease of use, Android encapsulates some classes, such as Asynctask, Handlerthread, etc., in the daily development process, we often need to perform some time-consuming operations, For example, to initiate a network request, in consideration of other external factors such as speed, the server may not immediately respond to our request, if you do not put this operation in the sub-thread to execute, it will cause the main thread is blocked, today we are from the basis of multi-threaded discussion

First, the basic usage of threads

For Andorid multithreading, we're talking about thread and Runnable. Normally we'll start a new thread as follows

1) inherit from thread to create child thread

Define a thread that only needs to create a new class to inherit from thread, and then override the parent class's Run method to

[Java]View PlainCopy
    1. /**
    2. * Inherit thread Create child thread
    3. */
    4. Class MyThread extends Thread {
    5. @Override
    6. public Void Run () {
    7. //handling of specific logic
    8. }
    9. }

So how do you start this thread? Just create an instance of MyThread and call its start () method so that the code in the Run () method runs on the child thread, as follows:

[Java]View PlainCopy
    1. New MyThread (). Start ();

2) Implement Runnable interface to create child threads

Inheritance is highly coupled, and more often we choose to implement a Runnable interface to implement a sub-thread, as follows:

[Java]View PlainCopy
    1. /**
    2. * Implement Runnable interface to create child threads
    3. */
    4. Class MyThread implements Runnable {
    5. @Override
    6. public Void Run () {
    7. //handling of specific logic
    8. }
    9. }

If you use this notation, the method of starting the thread also needs to be changed accordingly, as follows:

[Java]View PlainCopy
    1. MyThread MyThread = new MyThread ();
    2. New Thread (MyThread). Start ();

The thread constructor takes a Runnable parameter, and the new MyThread is the object that implements the Runnable interface, so it can be passed directly into the thread's constructor, and then it's the same as above, calling the STA of thread RT () method, the code in the Run () method runs in the child thread.

3) Create child threads directly using anonymous classes

[Java]View PlainCopy
    1. New Thread (new Runnable () {
    2. @Override
    3. public Void Run () {
    4. //handling of specific logic
    5. }
    6. }). Start ();

If you do not want to define a class to implement the Runnable interface, you can also use the same way as the anonymous class, this implementation is the most common to us

These are the same things that we used when we created the child threads, basically the same as in Java

4) The difference between Thread and Runnable

In fact, thread is also a Runnable, it implements the Runnable interface, in the Thread class has a Runnable type of Target field, representing the task to be executed in this sub-thread, the code is as follows:

Thread Part Source code:

[Java]View PlainCopy
  1. Public class Thread implements Runnable {
  2. /* What'll be run. * *
  3. private Runnable target;
  4. /* The group of this thread * /
  5. Private Threadgroup Group;
  6. private String name;
  7. /* 
  8. * The requested stack size for this thread, or 0 if the creator did
  9. * Not specify a stack size. It's up to the VM to do whatever it
  10. * Likes with this number; Some VMs would ignore it.
  11. */
  12. private long stackSize;
  13. /** 
  14. * Initialize thread and add thread to Threadgroup
  15. *
  16. * @param g
  17. * @param target
  18. * @param name
  19. * @param stackSize
  20. */
  21. private void init (Threadgroup g, Runnable Target, String name, long stackSize) {
  22. Java.lang.Thread parent = CurrentThread ();
  23. //group parameter is empty, gets the thread-only group for the current thread
  24. if (g = = null) {
  25. g = Parent.getthreadgroup ();
  26. }
  27. this.group = g;
  28. this.name = name;
  29. //Set Target
  30. this.target = target;
  31. / * Stash The specified stack size in case the VM cares * /
  32. this.stacksize = stackSize;
  33. }
  34. Public Thread () {
  35. Init (null, null, null, 0);
  36. }
  37. Public Thread (Runnable target) {
  38. Init (null, target, null, 0);
  39. }
  40. Public Thread (threadgroup Group, Runnable target) {
  41. Init (group, Target, null, 0);
  42. }
  43. Public Thread (Runnable target, String name) {
  44. Init (null, target, name, 0);
  45. }
  46. Public Thread (threadgroup Group, Runnable Target, String name) {
  47. Init (group, target, name, 0);
  48. }
  49. Public Thread (threadgroup Group, Runnable Target, String name,
  50. long StackSize) {  
  51. Init (group, target, name, stackSize);
  52. }
  53. /** 
  54. * Start a new thread and execute the target run function if target is not empty
  55. * No person executes the current object's run () method
  56. */
  57. public synchronized Void Start () {
  58. //Call Nativecreate to start a new thread
  59. Nativecreate (This, stackSize, daemon);
  60. started = true;
  61. }
  62. @Override
  63. public Void Run () {
  64. if (target! = null) {
  65. Target.run ();
  66. }
  67. }
  68. }

Above is the part of thread source code, we see in fact thread also implemented the Runnable interface, and ultimately the thread is executed by the Runnable, rather than thread,thread just Runnable packaging, and through some states to manage the thread With scheduling, Runnable defines an executable task that has only one run () function with no return value, as follows:

[Java]View PlainCopy
  1. Public interface Runnable {
  2. /** 
  3. * When a object implementing interface <code>Runnable</code> is used
  4. * To create a thread, starting the thread causes the object ' s
  5. * <code>run</code> method to being called in that separately executing
  6. * Thread.
  7. * <p>
  8. * The general contract of the method <code>run</code> are it may
  9. * Take any action whatsoever.
  10. *
  11. * @see Java.lang.thread#run ()
  12. */
  13. public abstract Void run ();
  14. }

When a thread is started, the Target's run () function is executed in the child thread if the target of the thread is not NULL, otherwise the virtual machine executes the thread's own run () function

Second, the thread wait, sleep, join, yield

The basic usage of thread is relatively simple, usually the replication run () function, and then the thread's start () method starts the thread, and next we look at the difference between wait, sleep, join, yield

1) Wait

When a thread executes to the wait () method, it enters into a waiting pool associated with the object while freeing the object's machine lock so that other threads can access it, the user can use Notify, Nitifyall, or specify sleep time to wake up the thread in the current waiting pool, note: Wait () , notify (), Notifyall () must be placed in the Synchronized block, or an exception will be thrown

2) Sleep

This function is a static function of thread that causes the calling thread to go to sleep because sleep () is a static method of the thread class, so it cannot alter the object lock, so when the sleep () method is called in a Synchronized block, the thread sleeps, But the object's lock is not released, and other threads cannot access the object, even if sleep holds the lock on the object

3) Join

Wait for the target thread to finish before continuing execution

4) yield

Thread comity, the target thread is transitioning from the running state to the ready state, that is, giving up execution permissions so that other threads can take precedence, but other threads can take precedence over unknown

Third, thread pool

When we need to frequently create multiple threads for time-consuming operations, it is not a good way to go through the new thread every time, and every time new thread creates and destroys objects with poor performance, threads lack unified management, may create unlimited new threads, compete with each other, May consume too much system resources lead to deadlock, and lack of regular execution, periodic execution, thread interruption and other functions, Java provides 4 kinds of thread pool, it can effectively manage, dispatch threads, avoid excessive waste of system resources, its advantages are as follows:

1) Reuse of existing threads, reduce object creation, cost of destruction

2) can effectively control the maximum number of concurrent threads, improve the utilization of system resources, while avoiding excessive resource competition, to avoid clogging

3) Provide the functions of timing execution, regular execution, single thread, concurrency control, etc.

Simply put, the thread pool principle is simple to explain is to create multiple threads and management, the task submitted to the thread will be assigned to the thread pool to execute, through the thread pool unified scheduling, management makes multithreaded use more simple and efficient, such as:

The thread pool implements the Executorservice interface, and the interface defines the interface that is required to implement it, and its implementation is threadpoolexecutor and Scheduledthreadpoolexecutor. Threadpoolexecutor is the most common thread pool implementation we use, Scheduledthreadpoolexecutor is used to perform periodic tasks, and usually we do not create a thread pool directly from new, because the process of creating parameters is relatively complex, So the JDK provides us with a Executor factory class to simplify this process.

Guidelines for using thread pools:

1) do not queue up tasks that synchronize the results of other tasks, which can lead to deadlocks, where all the threads in the deadlock are occupied by tasks that wait for the result of the queued task, which in turn cannot execute because all threads are busy

2) Understand the task, to effectively adjust the size of the thread pool, you need to understand the tasks being queued and what they are doing

3) The size of the thread pool is basically to avoid two types of errors, too few threads or too many threads, fortunately for most applications, too much and too little leeway between the wide

Today's introduction of the basic are some of the theoretical things, and some may seem boring, we should understand it, and to Friday, I wish you a happy weekend

Reference: Guo Shindi Line code, Android advanced

On Android multi-threaded programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.