Android multithreaded Research (9)--Thread lock lock

Source: Internet
Author: User

We used the Synchronized keyword in front of the thread synchronization problem, and today we look at the thread lock lock provided after Java 5.0.


The implementation class of the lock interface provides a more flexible and extensive locking object operation than using the Synchronized keyword, and it is an object-oriented way to lock objects.

@Overridepublic void Run () {while (true) {lock lock = new Reentrantlock (); try {lock.lock (); Thread.Sleep (New Random (). Nextint (3000)); String data = ReadData (); System.out.print ("reads data:" + data);} catch (Interruptedexception e) {e.printstacktrace ();} Finally{lock.unlock ();}}}

Read and write locks: divided into reading and writing locks, multiple read locks are not mutually exclusive, read lock and write lock mutex, write lock and write lock mutex, which is controlled by the JVM.

Import Java.util.random;import Java.util.concurrent.locks.readwritelock;import Java.util.concurrent.locks.reentrantreadwritelock;public class Readwritelocktest {static Readwritelock rwl = new Reentrantreadwritelock ();p rivate static String data = Null;public static void Main (string[] args) {Runnable runnable1 = NE W MyRunnable1 (); Runnable runnable2 = new MyRunnable2 (); for (int i=0; i<3; i++) {new Thread (RUNNABLE1). Start (); new Thread (Runnable2). Start ();}} Static class MyRunnable1 implements runnable{@Overridepublic void Run () {WriteData ("" + New Random (). Nextint (100));}} Static class MyRunnable2 implements runnable{@Overridepublic void Run () {readdata ();}} private static void WriteData (String var) {Rwl.writelock (). Lock (); try {System.out.println (Thread.CurrentThread (). GetName () + "prepare to write"); Thread.Sleep (New Random () nextint);d ata = var; System.out.println (Thread.CurrentThread (). GetName () + "write Complete");} catch (Interruptedexception e) {e.printstacktrace ();} Finally{rwl.writelock (). Unlock ();}} Private static void ReadData () {Rwl.readlock (). Lock (); Lock the try {System.out.println () with a read lock (Thread.CurrentThread (). GetName () + "ready to read"); Thread.Sleep (New Random (). Nextint (3000)); System.out.println (Thread.CurrentThread (). GetName () + "read Complete");} catch (Interruptedexception e) {e.printstacktrace ();} Finally{rwl.readlock (). Unlock ();}}}

Friends who have used hibernate framework may know that Hibernate query database has a caching mechanism, if a certain data exists in memory can be read concurrently, if there is no data in the cache need to be mutually exclusive to fetch data from the database.

Import Java.util.hashmap;import Java.util.map;import Java.util.concurrent.locks.reentrantreadwritelock;public Class Cachedemo {Private map<string, object> cache = new hashmap<string, object> ();p ublic static void Main (STR Ing[] args) {}private Reentrantreadwritelock rwl = new Reentrantreadwritelock ();/** * implements multiple concurrent reads, mutually exclusive write  * @param key * @ret Urn */public object GetData (String key) {Rwl.readlock (). Lock (); object value = Null;try{value = Cache.get (key); if (value = = NULL) {Rwl.readlock (). Unlock ();  Release read lock Rwl.writelock (). Lock ();   Add write lock try{if (value = = null) {  //drop other lines loads load data value = "Go to database Query";//simulate querying from the database if (value = = null) {//todo throws an exception}}}finally{ Rwl.writelock (). Unlock ();} Rwl.readlock (). Lock ();  The lock is returned to the read thread}}finally{rwl.readlock (). Unlock ();} return value;}}
The approximate process for getting the data above is as follows:

1. Get read lock, read data

2. If there is data, return directly and release the read lock to allow other threads to read.

3. If there is no data in memory, write memory from database, release read lock and add write lock (so write data can be mutually exclusive)

4, read into memory to release the write lock and also read back the lock (and the back of the Unlock () corresponding)

5, if there are multiple threads at the same time when the write lock is added, only one of the threads can grab the lock, and when the lock thread releases the write lock, the other thread will grab the write lock, but at this point the data has been written to memory, it is necessary to determine if the memory data is NULL if NOT NULL then the write lock is released


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.