Multi-thread lock lock and read-write lock Readwritelock

Source: Internet
Author: User

Another lock lock is provided after the JDK1.5. Lockimplementations provide a wider synchronized range of locking operations than can be obtained using methods and statements. This implementation allows for a more flexible structure that can have very different properties and can support multiple related Condition objects.

A lock is a tool that controls the access of multiple threads to a shared resource. Typically, a lock provides exclusive access to a shared resource. Only one thread can get a lock at a time, and all access to the shared resource requires a lock first. However, some locks may allow concurrent access to shared resources, such as ReadWriteLock read locks.

synchronizedThe use of a method or statement provides access to an implicit monitor lock associated with each object, but forces all lock acquisition and deallocation to appear in a block structure: When multiple locks are acquired, they must be disposed in reverse order, and all locks must be released in the same lexical scope as all locks are fetched.

and lock locking must be followed by our search to release the lock:

Lock L = ...;      L.lock ();     try {         //access the resource protected by this lock     } finally {         l.unlock ();     

The synchronized can be rewritten as follows:

Package Andy.thread.test;import Java.util.concurrent.locks.lock;import java.util.concurrent.locks.reentrantlock;/ * * @author zhang,tianyou * @version November 8, 2014 PM 11:30:10 */public class Threadlocktest {public static void main (string[ ] args) {A A = new A (); New Thread (New Runnable () {@Overridepublic void run () {while (true) {try {thread.sleep ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} A.PRINTFA (Thread.CurrentThread (). GetName () + "Hello, my is A");}}). Start (); New Thread (New Runnable () {@Overridepublic void run () {while (true) {try {Thread.Sleep]} catch (Interruptedex Ception e) {//TODO auto-generated catch Blocke.printstacktrace ();} A.PRINTFA (Thread.CurrentThread (). GetName () + "Hello, my is B");}}). Start ();}  Static class A {//definition lock lock locks lock = new Reentrantlock ();p ublic void Printfa (String name) {lock.lock ();//Add Lock lock try {for (int i = 0; i < name.length (); i++) {System.out.print (Name.charat (i));} System.out.println ();} finally {LoCk.unlock ()//The lock is freed regardless of whether the lock content is executed}}} 



Lock also provides a read-write lock Readwritelock:

1 读取锁Can be persisted by multiple reader threads at the same time

2  写入锁is exclusive.

Readwritelock rwl = new Reentrantreadwritelock ();

One, read lock operation

Rwl.readlock (). Lock ();

Rwl.readlock (). Unlock ();


Second, write lock operation

Rwl.writelock (). Lock ();

Rwl.writelock (). Unlock ();


The implementation reads and writes as follows:

Package Andy.thread.test;import Java.util.random;import Java.util.concurrent.locks.readwritelock;import java.util.concurrent.locks.reentrantreadwritelock;/** * @author zhang,tianyou * @version November 8, 2014 11:44:01 * *  public class Readwritelocktest {public static void main (string[] args) {Final A A = new A (), for (int i = 0; i < 3; i++) {New Thread () {public void run () {while (true) {A.get ()}}}. Start (); new Thread () {public void run () {while (true) {A.put (New Random (). Nextint (10000));}}. Start ();}}} Class A {private Object data = null;//shares data, only one thread can write the data, but multiple threads can read the data at the same time. Readwritelock rwl = new Reentrantreadwritelock ();p ublic void Get () {Rwl.readlock (). Lock (); try {System.out.println ( Thread.CurrentThread (). GetName () + "be ready to read data!"); Thread.Sleep ((Long) (Math.random () * 1000)); System.out.println (Thread.CurrentThread (). GetName () + "has read data:" + data);} catch (Interruptedexception e) {e.printstacktrace ();} finally {Rwl.readlock (). Unlock ();}} public void put (Object data) {RWL. Writelock (). Lock (); try {System.out.println (Thread.CurrentThread (). GetName () + "be ready to write data!"); Thread.Sleep ((Long) (Math.random () *)); this.data = data; System.out.println (Thread.CurrentThread (). GetName () + "have write data:" + data);} catch (Interruptedexception e) {e.printstacktrace ();} finally {Rwl.writelock (). Unlock ();}}



The results are as follows:

Thread-0 is ready to read data! Thread-4 is ready to read data! Thread-2 is ready to read data! Thread-0have Read Data:nullthread-2have read Data:nullthread-4have read data:nullthread-1 be ready to write data! Thread-1 has write data:5730thread-1 is ready to write data! Thread-1 has write data:7997thread-1 is ready to write data! Thread-1 has write data:2306thread-1 is ready to write data! Thread-1 has write data:8944thread-1 is ready to write data! Thread-1 has write data:8039thread-1 is ready to write data! Thread-1 has write data:6844thread-1 is ready to write data! Thread-1 has write data:2969thread-1 is ready to write data!





Multi-thread lock lock and read-write lock Readwritelock

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.