A simple example of java-reentrantreadwritelock

Source: Internet
Author: User

Content: Shared when reading a lock, the mutex (visible running result) is implemented by AQS.

public class Reentrantreadwritelocktest {static class MyObject {private Object object;private readwritelock lock = new Ree Ntrantreadwritelock ();p ublic void Get () {Lock.readlock (). Lock (); System.out.println (Thread.CurrentThread (). GetName () + "ready to read Data!"); try {thread.sleep (New Random (). Nextint (1000)); System.out.println (Thread.CurrentThread (). GetName () + "read data:" + This.object);} catch (Interruptedexception e) {e.printstacktrace ();} finally {Lock.readlock (). Unlock ();}} public void put (Object object) {Lock.writelock (). Lock (); System.out.println (Thread.CurrentThread (). GetName () + "prepare to write Data"), try {thread.sleep (New Random (). Nextint (1000)); This.object = object; System.out.println (Thread.CurrentThread (). GetName () + "Write data for" + This.object);} catch (Interruptedexception e) {e.printstacktrace ();} finally {Lock.writelock (). Unlock ();}} public static void Main (string[] args) throws Interruptedexception {final MyObject MyObject = new MyObject (); Executorservice executor = Executors.newcachedthreadpool (); for (int i = 0; I < 3; i++) {Executor.execute (new Runnable () {@Overridepublic void Run () {for (int j = 0; J < 5; j + +) Myobject.put (new Random () . Nextint (1000));});} for (int i = 0; i < 3, i++) {Executor.execute (new Runnable () {@Overridepublic void Run () {for (int j = 0; J < 5; J + +) ) Myobject.get ();}});} Executor.shutdown ();}}


Operation Result:



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

A simple example of java-reentrantreadwritelock

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.