读写锁:多个线程同时读共享资源,但是有线程对共享资源写,则其他线程不能读 也不能写

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁:多个线程同时读共享资源,但是有线程对共享资源写,则其他线程不能读 也不能写
 * 读读共存;读写不共存;写写不共存
 * 写:原子+独占
 */
public class ReadWriteLockDemo {
    public static void main(String[] args){
        final MyCache myCache = new MyCache();
        for (int i = 0; i < 6; i++) {
            final int tem = i;
            Thread thread =  new Thread(new Runnable() {
                @Override
                public void run() {
                    myCache.put(tem+"",tem+"");
                }
            });
            thread.setName(i+"");
            thread.start();
        }

        for (int i = 0; i < 6; i++) {
            final int tem = i;
            Thread thread =  new Thread(new Runnable() {
                @Override
                public void run() {
                    myCache.get(tem+"");
                }
            });
            thread.setName(i+"");
            thread.start();
        }
    }
}
//资源类
class MyCache{
     private volatile Map<String,Object> map = new HashMap<>();
    //private Lock lock = new ReentrantLock();
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key,Object value){
        //写限制 必须写入完成后才可另一个线程开始
        lock.writeLock().lock();

        try {
            System.out.println(Thread.currentThread().getName()+"正在写入");
            Thread.sleep(997);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
        }


    }
    public void get(String key){
        //读不限制
        lock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName()+"正在读取");
            Thread.sleep(997);
            Object result =  map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取完成" +result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }


    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的示例程序,可以满足您的要求: ```c++ #include <iostream> #include <cstdlib> #include <thread> #include <mutex> #include <condition_variable> #include <chrono> using namespace std; mutex mtx; // 互斥锁 condition_variable cv; // 条件变量 bool ready = false; // 标志位,表示数据是否准备好 int data = 0; // 共享数据 void writer() { for (int i = 0; i < 10; i++) { unique_lock<mutex> lck(mtx); data = i; // 写入数据 ready = true; // 标记数据已经准备好 cv.notify_all(); // 通知所有等待的线程 lck.unlock(); // 解锁互斥锁 this_thread::sleep_for(chrono::milliseconds(100)); // 等待一段时间 } } void reader(int id) { while (true) { unique_lock<mutex> lck(mtx); while (!ready) { // 如果数据没准备好,就等待通知 cv.wait(lck); } cout << "Reader " << id << " read data: " << data << endl; // 读取数据 ready = false; // 标记数据已经被读取 lck.unlock(); // 解锁互斥锁 this_thread::sleep_for(chrono::milliseconds(500)); // 等待一段时间 } } int main() { thread t1(writer); // 创建线程 thread t2(reader, 1); // 创建线程1 thread t3(reader, 2); // 创建线程2 t1.join(); // 等待线程结束 t2.join(); // 等待线程1结束 t3.join(); // 等待线程2结束 return 0; } ``` 在这个程序中,我们使用了一个互斥锁和一个条件变量来实现读写锁的功能。线程每次写入数据后,都会将标志位设置为 true,并通知所有等待的线程线程每次读取数据前,都会检查标志位是否为 true,如果为 false,就等待通知。这样,就能保证操作和操作之间的互斥性。 注意,这个程序只是一个简单的示例,实际的读写锁需要更复杂的实现。在实际的应用中,您可能需要考虑更多的情况,例如并发性、优先级等等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值