Android Concurrent Programming

Source: Internet
Author: User

Concurrent programming for Android, multithreaded development, and the multithreaded development model of Android are also derived from the multithreaded model in Java .
So this article will first talk about some of the multithreading concepts in Java, and then explain the specific classes involved, and finally dive into the concurrency scenarios and practices in Android.

concurrency what is concurrency

A very simple chestnut, when you are in the side of the same, while watching a small video , while doing two things, this is concurrency.

Cough, the young man temperance.

Concurrency Benefits Increase Resource utilization

When a task does not fully consume system resources, concurrency can be used to improve resource utilization and to accomplish tasks faster.

When your right hand is doing something, is the left hand doing nothing? Then use it, too.
(A party, a horse-riding man said his left and right mutual beats (LU) special).

More streamlined on program tasks

Take the last chestnut, what the left hand does, what the right hand does, the task is clearly assigned, and can be carried out at the same time, both improve efficiency, logic and clear.

A better Response program

This take Android client to lift a chestnut, upload pictures, the current interface or normal operation no card dead, the picture is also normal upload, not only to ensure that the interface is responding, but also to ensure that the picture can be uploaded.

The cost of concurrent risk concurrency
    • More resources are required.
    • Designing good one concurrent programs is not easy.
    • Concurrent resource interaction issues are complex.
Concurrency vulnerability
    • System instability due to misuse of resources
    • Results not in conformity with expectations
    • Bugs are hard to troubleshoot
What is the thread post process?

In the case of Android apps, an app is generally a process, (except for the special means to open up a number of processes, where this topic is not in-depth, is a one-to-many relationship).

What is a thread

A process is a general term for a program, a task, but not a task, and a thread is the one that actually executes the task, so the thread is created by the process, and a process can create multiple threads.

Thread can dispatch resources and so on, here just need to understand the general concept is good, if you want to drill down to learn the operating system .

Process-to-thread relationships

The brain is the equivalent of CPU, want to do one thing, this task is a process, need to use the hands and feet and other organs to complete the task, and the hands and feet can be understood as a thread, to do a different thing, to complete the task.

Single Thread

Or you can use Android to lift chestnuts, which is called the UI thread when you're working on your phone (which will be explained later). While a basic app that doesn't require complex functionality, there's only one UI thread that interacts with us, so the app is a single-threaded one. The general program for the user-oriented thread is the UI thread, also known as the main thread, a single-threaded program, in fact, there is only one main thread of programs.

Multithreading

Multiple processes can be considered concurrent, but what we call concurrency scenarios are mostly in one process, and concurrency is done by threads, and multiple threads perform tasks concurrently, called Concurrency.

The following are multithreaded tasks:

Problems encountered during multi-threaded concurrency 1. Resource sharing

A thread to write files C,b thread also to write file C, this time as if you hold two pens at the same time to write things on the paper, write out what you do not know.

At this time we need a lock -like thing, when C is written by a, B can not write, b to wait until a is finished to continue to write.

As to what the lock is going to be in the back.

3. Deadlock problem

The four conditions for deadlocks are:

    • No preemption: No preemption

    • Holding and waiting: Hold and wait

    • Mutex: Mutual exclusion

    • Cyclic wait: circular waiting

The prevention of deadlocks is at least one of the four conditions that destroys "no preemption", destroys "hold Wait", destroys "resource mutexes", and destroys "cyclic waiting."

As an example:

A in B over there circumcision, B cut a broken, a to occupy B bed, B to lose money, B to a let bed just give the cash. The two sides are deadlocked.

How the thread is going to use

In Java, a thread usually refers to Thread the class, or the implementation Runnable of the class, in fact, Thread This class is also implemented Runnable interface, you can look at Runnable the interface code:

Inside is a run method that needs to be implemented.

Look again at Thread the declaration of the class:

is indeed a class that has been implemented Runnable .

Then the thread class has start() methods, and run() methods, which are run() called directly by method
Get information:

Find out that the threads are actually on the same thread as the outside.

start()the information given by the calling method is:

found that the thread name is different, with start it opens a new thread, and run is executed on the current thread.

In addition, after the Java1.5, there are callable, future and Futuretask, here is not detailed introduction, but also wired to wait,
Yield, sleep, etc. will be described in detail in the next chapter.

Priority of the thread

In Java, the priority of a thread is 1~10, and the default is 5. 1 minimum, 10 maximum. There are three constants in the thread class:

    • min_priority = 1

    • Norm_priority = 5

    • Max_priority = 10

The thread priority in the same thread pool is the same.

The JVM will preempt the scheduling based on the priority of the thread, but the priority of the thread can only guarantee a higher probability of preemption, and cannot guarantee the order of execution of the thread, so it is not too dependent on the priority of the set thread.

Thread pool

The frequent creation and destruction of threads can cause a significant decrease in performance, which is certainly not what you want.

The advent of the thread pool is to solve this problem by providing different thread pool mechanisms in Java to effectively improve resource utilization.

Creating a thread directly in the code, runnable to start, or run is prone to unpredictable problems, and at the beginning of java1.5, the Java.util.concurrent package is introduced, with a concurrent framework: Executor ExecutorService Instead of directly manipulating the thread class, which Executors is used to create the thread pool, there are many static methods inside to create the thread pool you want, without having to manually create the implementation.
Take a look at the approximate members and relationships of classes and interfaces in executor:

The next chapter will cover how these classes are used and what the features are.

Queue

The mention of queues in Java is sure Queue to be remembered, whereas thread queues use this as an BlockingQueue interface that concurrent has several classes in the package that implement this interface.

Introduce the common methods of Blockingqueue

will be returned unexpectedly success will block set wait time
Into the queue Add (E) Offer (e) Put (e) Offer (E, timeout, unit)
Out queue Remove () Poll () Take () Poll (time, unit)
View values Element () Peek () None None
Line Shuo Full lock

In front of the deadlock, the deadlock is caused by improper use of a phenomenon, and the lock here is manual intervention, let concurrency follow your meaning to go.

The locks in Java are synchonrized, lock. The lock appears primarily to address thread safety issues.

The state of the thread is explained in the next chapter on the mechanism of locking, because the state of the thread affects the lock.

Thread-Safe collections

Because multithreaded access to resources can result in inconsistent data or data contamination, some collections are handled with some lock or synchronization mechanisms.

Thread-Safe collections are: HashTable, synchronizedcollection, concurrenthashmap, vectors, and so on.

The first prerequisite for thread Shuo insecurity is in cases where multiple threads access the same object .

Android Concurrent 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.