Research on multiple threads in Android (9) -- read/write locks and multiple threads in android

Source: Internet
Author: User
Tags java util

Research on multiple threads in Android (9) -- read/write locks and multiple threads in android
I. What is a lock?

The lock interfaces and classes in the Java util. concurrent. locks package are as follows:


First look at a piece of code:

Package com. codeing. snail Il. test; public class ReadWriteLockTest {public static void main (String [] args) {final Output output = new Output (); new Thread () {public void run () {while (true) {output. output ("codeingsnil ");}};}. start (); new Thread () {public void run () {while (true) {output. output ("Sunshine Xiaoqiang ");}};}. start ();} static class Output {public void output (String name) {char [] arry = name. toCharArray (); for (int I = 0; I <arry. length; I ++) {System. out. print (arry [I]);} System. out. println ();}}}

The output result is as follows:

If we want both the "codeingsnil" and "Sunshine Xiaoqiang" strings to be completely output, we need to use the synchronized keyword to declare the output part as follows:

public synchronized void output(String name){char[] arry = name.toCharArray();for(int i = 0; i < arry.length; i++){System.out.print(arry[i]);}System.out.println();}

In fact, in addition to the synchronized keyword, you can also use Lock to implement synchronization.

ReentrantLock lock = new ReentrantLock();public void output(String name){lock.lock();try{char[] arry = name.toCharArray();for(int i = 0; i < arry.length; i++){System.out.print(arry[i]);}System.out.println();}finally{lock.unlock();}}
The above Code uses try... the finally statement block is used to prevent exceptions from failing to execute the unlock method. ReentrantLock is the Lock implementation class. The Lock function is similar to synchronized, but more object-oriented, to implement synchronization, you must use the same lock object.

2. What are read/write locks? read/write locks are divided into read locks and write locks. Multiple read locks are not mutually exclusive. Read locks and write locks are mutually exclusive. Write locks and write locks are mutually exclusive. The following is an example of a cache in the API documentation:

class CachedData {Object data;volatile boolean cacheValid;final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();void processCachedData() {     rwl.readLock().lock();     if (!cacheValid) {        // Must release read lock before acquiring write lock        rwl.readLock().unlock();        rwl.writeLock().lock();        try {          // Recheck state because another thread might have          // acquired write lock and changed state before we did.          if (!cacheValid) {            data = ...            cacheValid = true;          }          // Downgrade by acquiring read lock before releasing write lock          rwl.readLock().lock();        } finally {          rwl.writeLock().unlock(); // Unlock write, still hold read        }     }     try {       use(data);     } finally {       rwl.readLock().unlock();     }     }}
If there are multiple threads to read data, the first thread comes in and writes data to the previous write lock (first releases the read lock). After the write is completed, the write lock is downgraded to the read lock (15th rows ), when reading data, other threads do not affect each other after reading the lock. This improves reading efficiency.




Android multithreading Error

You cannot operate the UI in other threads. To operate the UI, you need to create a Handler, use the Handler to obtain the message in the thread, and then update the UI.

An error occurs when multiple threads of android call the service at the same time.

Only one service instance is allowed to call the same service.
The first service call will trigger the onCreate () event, and then the call will only trigger onStart.
Therefore, you must consider the processing mechanism and then write code.

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.