zoukankan      html  css  js  c++  java
  • ReadWriteLock读写锁

    ReadWriteLock维护了一对锁,读锁可允许多个读线程并发使用,写锁是独占的。

    下面通过一个简单的例子来了解ReadWriteLock。

     1 package com.ccfdod.juc;
     2 
     3 import java.util.concurrent.locks.ReadWriteLock;
     4 import java.util.concurrent.locks.ReentrantReadWriteLock;
     5 
     6 /**
     7  * 写写/读写,需要互斥
     8  * 读读,不需要互斥
     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             @Override
    17             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                 @Override
    27                 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     //
    43     public void get() {
    44         lock.readLock().lock();    //上锁
    45         try {
    46             System.out.println(Thread.currentThread().getName() + " : " + number);
    47         } finally {
    48             lock.readLock().unlock();    //释放锁
    49         }
    50     }
    51     
    52     //
    53     public void set(int number) {
    54         lock.writeLock().lock();    //上锁
    55         try {
    56             System.out.println(Thread.currentThread().getName());
    57             this.number = number;
    58         } finally {
    59             lock.writeLock().unlock();    //释放锁
    60         }
    61     }
    62 }
  • 相关阅读:
    ural 1146. Maximum Sum(动态规划)
    ural 1119. Metro(动态规划)
    ural 1013. K-based Numbers. Version 3(动态规划)
    Floyd算法
    杭电21题 Palindrome
    杭电20题 Human Gene Functions
    杭电15题 The Cow Lexicon
    杭电三部曲一、基本算法;19题 Cow Bowling
    杭电1002 Etaoin Shrdlu
    Qt 学习之路 2(37):文本文件读写
  • 原文地址:https://www.cnblogs.com/ccfdod/p/6417655.html
Copyright © 2011-2022 走看看