zoukankan      html  css  js  c++  java
  • 线程之ReadWriteLock

    import java.util.Random;
    import java.util.concurrent.locks.ReadWriteLock;
    import java.util.concurrent.locks.ReentrantLock;
    import java.util.concurrent.locks.ReentrantReadWriteLock;

    public class ThreadReadWriteLock {

    /**
    * 读写锁
    * 读得时候还能读
    * 读的时候不能写
    * 写的时候不能读
    * 写的时候不能写
    */
    public static void main(String[] args) {
    final ReadWrite readWrite = new ReadWrite();
    for(int i=0;i<3;i++){
    new Thread(){
    public void run() {
    while(true){
    readWrite.read();
    }
    }}.start();
    new Thread(){
    public void run() {
    while(true){
    readWrite.write(new Random().nextInt(1000));
    }
    }}.start();
    }
    }
    }
    class ReadWrite{
    Object data = null;
    ReadWriteLock rwl = new ReentrantReadWriteLock();
    public void read(){
    rwl.readLock().lock();
    try{
    System.out.println(Thread.currentThread().getName()+" ready to read data");
    Thread.sleep((long)(Math.random()*1000));
    System.out.println(Thread.currentThread().getName()+" has read " + data);
    }catch(InterruptedException e){
    e.printStackTrace();
    }finally{
    rwl.readLock().unlock();
    }
    }
    public void write(Object data){
    rwl.writeLock().lock();
    try{
    System.out.println(Thread.currentThread().getName()+" ready to write data");
    this.data = data;
    Thread.sleep((long)(Math.random()*1000));
    System.out.println(Thread.currentThread().getName()+" has written " + data);
    }catch(InterruptedException e){
    e.printStackTrace();
    }finally{
    rwl.writeLock().unlock();
    }

    }
    }
    复制代码
  • 相关阅读:
    eclips断点调试
    单位换算
    信息论与编码复习
    嵌入式学习笔记
    DAVINCI项目日志
    英语考试方法
    虚拟机安装Ubuntu的上网设置(有线网络和无线网络)
    重装系统必须备份的几种数据
    linux笔记
    word应用技巧
  • 原文地址:https://www.cnblogs.com/dayhand/p/2812069.html
Copyright © 2011-2022 走看看