操作系统之同步及顺序执行

读写锁

代码:

import
java.util.concurrent.locks.ReentrantReadWriteLock;

 

/**

 * 使用读写锁,可以实现读写分离锁定,读操作并发进行,写操作锁定单个线程

 * 

 * 如果有一个线程已经占用了读锁,则此时其他线程如果要申请写锁,则申请写锁的线程会一直等待释放读锁。

 * 如果有一个线程已经占用了写锁,则此时其他线程如果申请写锁或者读锁,则申请的线程会一直等待释放写锁。

 * @author

 *

 */

public class MyReentrantReadWriteLock {

    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

     

       public static void main(String[] args)  {

          
final MyReentrantReadWriteLock test = new MyReentrantReadWriteLock();

           


          
new Thread(){

              
public void run() {

                   test.get(Thread.currentThread());

                   test.write(Thread.currentThread());

              
};

          
}.start();

           


          
new Thread(){

              
public void run() {

                   test.get(Thread.currentThread());

                   test.write(Thread.currentThread());

              
};

          
}.start();

           


      
}  

       

       /**

        * 读操作,用读锁来锁定

        * @param thread

        */

       public void get(Thread thread) {

          
rwl.readLock().lock();

          
try {

              
long start = System.currentTimeMillis();

               
//System.currentTimeMillis()相当于是毫秒为单位

              
while(System.currentTimeMillis() -
start <= 1) {//相当于过了1毫秒

                   System.out.println(thread.getName()+"正在进行读操作");

              
}

              
System.out.println(thread.getName()+"读操作完毕");

          
} finally {

              
rwl.readLock().unlock();

          
}

       }

       /**

        * 写操作,用写锁来锁定

        * @param thread

        */

       public void write(Thread thread) {

          
rwl.writeLock().lock();;

          
try {

              
long start = System.currentTimeMillis();

               


              
while(System.currentTimeMillis() -
start <= 1) {

                   System.out.println(thread.getName()+"正在进行写操作");

              
}

              
System.out.println(thread.getName()+"写操作完毕");

          
} finally {

              
rwl.writeLock().unlock();

          
}

       }

}

结果抓图:[在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

心得

*Java中读写锁的例子就是互斥的例子,读锁能并发执行,写锁不能并发执行

一个代表写者wmutex,一个代表读者rmutex
读锁:
Wait(rmutex)

if Readcount=0 then wait(wmutex)
// Readcount代表读者数量,读者数量为0时,说明这是第一个读者就wait(wmutex),如果此时有写操作那么读者被阻断,没有的话wmutex减为0,占用写信号
Readcount :=Readcount +1;
Signal(rmutex)

perform read operation;


Wait(rmutex)

Readcount :=Readcount -1;

if Readcount=0 then signal(rmutex)
Signal(rmutex)

写锁:
Writer :
repeat

wait(wmutex);

写入文件;

signal(wmutex);*

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值