ReadWriteLock read/write lock, readwritelock read/write

Source: Internet
Author: User

ReadWriteLock read/write lock, readwritelock read/write

ReadWriteLock maintains a pair of locks. Read locks can be used by multiple read threads concurrently, and write locks are exclusive.

The following is a simple example to learn about ReadWriteLock.

1 package com. ccfdod. juc; 2 3 import java. util. concurrent. locks. readWriteLock; 4 import java. util. concurrent. locks. reentrantReadWriteLock; 5 6/** 7 * write/read/write, mutually exclusive 8 * read, mutex 9 */10 public class TestReadWriteLock {11 12 public static void main (String [] args) {13 ReadWriteLockDemo rw = new ReadWriteLockDemo (); 14 new Thread (new Runnable () {15 16 @ Override17 public void run () {18 rw. set (int) (Math. random () * 101); 19} 20 21}, "Write :"). start (); 22 23 for (int I = 0; I <100; I ++) {24 new Thread (new Runnable () {25 26 @ Override27 public void run () {28 rw. get (); 29} 30 31}, "Read :"). start (); 32} 33} 34} 35 36 class ReadWriteLockDemo {37 38 private int number = 0; 39 40 private ReadWriteLock lock = new ReentrantReadWriteLock (); 41 42 // read 43 public void get () {44 lock. readLock (). lock (); // lock 45 try {46 System. out. println (Thread. currentThread (). getName () + ":" + number); 47} finally {48 lock. readLock (). unlock (); // release lock 49} 50} 51 52 // write 53 public void set (int number) {54 lock. writeLock (). lock (); // lock 55 try {56 System. out. println (Thread. currentThread (). getName (); 57 this. number = number; 58} finally {59 lock. writeLock (). unlock (); // release lock 60} 61} 62}

 

Related Article

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.