• 3.1.4 读写锁


    一、分为两种:公平和非公平

    线程 a b c d e
    公平:按顺序执行:a,b,d,e 读锁 c 写锁
    1.a,b 执行 c 堵塞,d,e 等待
    2.a,b执行结束 c获取锁 d,e堵塞等待
    3.c执行结束 d开始执行,然后在唤醒e

    非公平:
    1,2步骤相同
    3,c执行结束的时候,新来个线程 f读锁,在d没有唤醒的情况下,会获取读锁,然后在唤醒d,e




    package 第三章.读写锁;

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.locks.ReentrantReadWriteLock;

    /**
    * Created by zzq on 2018/1/23.
    */
    public class WebTestReadAndWriteLock {
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public static void main(String[] args) {
    final WebTestReadAndWriteLock lock = new WebTestReadAndWriteLock();
    // 建N个线程,同时读
    ExecutorService service = Executors.newCachedThreadPool();
    service.execute(new Runnable() {
    public void run() {
    lock.readFile(Thread.currentThread());
    }
    });
    service.execute(new Runnable() {
    public void run() {
    lock.readFile(Thread.currentThread());
    }
    });
    // 建N个线程,同时写
    ExecutorService service1 = Executors.newCachedThreadPool();
    service1.execute(new Runnable() {
    public void run() {
    lock.writeFile(Thread.currentThread());
    }
    });
    service.execute(new Runnable() {
    public void run() {
    lock.readFile(Thread.currentThread());
    }
    });
    service.execute(new Runnable() {
    public void run() {
    lock.readFile(Thread.currentThread());
    }
    });
    service1.execute(new Runnable() {
    public void run() {
    lock.writeFile(Thread.currentThread());
    }
    });
    }
    // 读操作
    public void readFile(Thread thread){
    lock.readLock().lock();
    boolean readLock = lock.isWriteLocked();
    if(!readLock){
    System.out.println("当前为读锁!");
    }
    try{
    for(int i=0; i<5; i++){
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println(thread.getName() + ":正在进行读操作……");
    }
    System.out.println(thread.getName() + ":读操作完毕!");
    }finally{
    System.out.println("释放读锁!");
    lock.readLock().unlock();
    }
    }
    // 写操作
    public void writeFile(Thread thread){
    lock.writeLock().lock();
    boolean writeLock = lock.isWriteLocked();
    if(writeLock){
    System.out.println("当前为写锁!");
    }
    try{
    for(int i=0; i<5; i++){
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println(thread.getName() + ":正在进行写操作……");
    }
    System.out.println(thread.getName() + ":写操作完毕!");
    }finally{
    System.out.println("释放写锁!");
    lock.writeLock().unlock();
    }
    }
    }
  • 相关阅读:
    Mybatis <set>标签
    Mybatis <where>标签
    Mybatis choose (when, otherwise)标签
    Mybatis <if>标签
    Mybatis <Sql>标签
    Mybatis配置详解
    [转]在浏览器的标签页显示网站标志图标(或指定图标)的方法
    【转】如何建立一个样式新颖的CSS3搜索框
    【转】css布局居中和CSS内容居中区别和对应DIV CSS代码
    作业:按钮控制打开关闭新窗口及新窗口按钮关闭父窗口
  • 原文地址:https://www.cnblogs.com/anxbb/p/8425537.html
Copyright © 2020-2023  润新知