`

Read Write Lock

阅读更多

        读的时候,实例的状态不会改变,“写”会改变线程的状态。

        这种模式,把读写分开,读之前获取锁定,不给写;写之前获取锁定,不给读。

        示例:WriteThread和ReadThread不断的读写公共的data。类Data中,有读写操作,他有一个lock,读写之前都会进行锁定。这个锁ReadWriteLock是按照如下实现的:

         如果真正写的数量大于0或者等待优先的等待写入者大于0,那么想读的线程进入等待状态,直到可以读为止,然后读入,这时读入人数加1,读完后如如人数减去1,使优先写入为真,并通知在这个对象中的所有等待线程。写的过程与这个类似。

public class ReadWriteLock extends Thread{
	private int readingReaders=0;  //实际在读取的线程数
	private int writingWriters=0;    //实际写入的线程数
	private int waitingWriters=0;  //等待的线程数
	private boolean preferWriter=true; //是否写入优先
	
	public synchronized void readLock() throws InterruptedException{
		while(writingWriters>0||(preferWriter &&waitingWriters>0)){
			wait();
		}
		readingReaders++;
	}
	public synchronized void readUnlock(){
		readingReaders--;
		preferWriter=true;
		notifyAll();
	}
	public synchronized void writeLock() throws InterruptedException{
		waitingWriters++;
		try{
			while(readingReaders>0||writingWriters>0){
				wait();
			}
		}finally{
			waitingWriters--;
		}
		writingWriters++;
	}
	public synchronized void writeUnlock(){
		writingWriters--;
		preferWriter=false;
		notifyAll();
	}
}

 

public class ReadThread extends Thread {
	private final Data data;
	public ReadThread(Data data){
		this.data=data;
	}
	public void run(){
		try{
			while(true){
				char[] readbuf=data.read();
				System.out.println(Thread.currentThread().getName()+" reads "+String.valueOf(readbuf));
			}
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}

}

 

import java.util.Random;

public class WriteThread extends Thread{
	private static final Random random=new Random();
	private final Data data;
	private String filler;
	private int index;
	public WriteThread(Data data,String filler){
		this.data=data;
		this.filler=filler;
	}
	public void run(){
		try{
			while(true){
				char c=nextChar();
				data.write(c);
				Thread.sleep(3000);
			}
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
	private char nextChar() {
		char c=filler.charAt(index);
		index++;
		if(index>=filler.length()){
			index=0;
		}
		return c;
	}

}

 

public class Main {
    public static void main(String[] arg){
    	Data data=new Data(10);
    	new ReadThread(data).start();
    	new ReadThread(data).start();
    	new ReadThread(data).start();
    	new ReadThread(data).start();
    	new ReadThread(data).start();
    	new ReadThread(data).start();
    	new WriteThread(data,"ABCDEFGHIJKLMNOPQRSTUVWXYZ").start();
    	new WriteThread(data,"abcdefghijklmnopqrstuvwxyz").start();
    }
}

 

 

 

 

分享到:
评论

相关推荐

    linux下实现高性能读写锁(read/write lock)

    在linux下按照windows的slim read/write lock算法实现的读写锁源码。

    ReadWriteLock

    一个Windows下C++读写锁的代码,实现共享读,独占写

    read-write-lock:读与写互斥,写与所有事物互斥

    var createMutex = require ( 'read-write-lock' ) var mutex = createMutex ( ) mutex . writeLock ( function ( release ) { // lol I've got a write lock which means that nobody else can do anything ...

    share_mem.tar.gz

    linux下实现高性能读写锁(read/write lock) 附带makefile,工程模板

    ATmega16A.rar_EEPROM_READ_avr_operation

    High-performance, Low-power Atmel AVR 8-bit Microcontroller &#1048698 Advanced RISC Architecture ...&#1048698 True Read-While-Write Operation &#822 Programming Lock for Software Security

    ReadWriteLock的使用

    ReadWriteLock的使用,实际上由于ReadWriteLock是一个接口,所以实际使用的是ReentrantReadWriteLock子类。同时ReadWriteLock的使用其实也是比较简单的,就是读写的锁的使用以及注意事项而已。

    微软内部资料-SQL性能优化3

     Discuss how lock manager uses lock mode, lock resources, and lock compatibility to achieve transaction isolation.  Describe the various transaction types and how transactions differ from batches....

    MySQL数据库:锁定与解锁.pptx

    数据库编程 锁定与解锁 课程目标 了解 —— 锁定和解锁的概念; 掌握 —— 锁定和解锁的设置; 锁定与解锁 MySQL提供了LOCK TABLES语句来锁定当前线程的表,语法格式如下: ...LOCK TABLES XS READ; 说明:LOCK TABLE

    cdma 读取数据强器

    轻松读取数据,更改esn,meid Unlock spc, MSL, SPC3, FSK, OTKSL, User Lock, MIN lock, SIM LOCK Programming: MIN, MDN, IMSI, NAM, PRL file, Phone Settings ... Read Write EEPROM, RAM, SDRAM area)

    java多线程设计模式 (PDF中文版, 附源码)

    第6章 Read-Write Lock——大家想看就看吧,不过看的时候不能写喔 第7章 read-Per-Message——这个工作交给你了 第8章 Worker Thread——等到工作来,来了就工作 第9章 Future——先给您这张提货单 第10章 Two-Phase...

    ATmega8515 datasheet.pdf

    True Read-While-Write Operation – 512 Bytes EEPROM Endurance: 100,000 Write/Erase Cycles – 512 Bytes Internal SRAM – Up to 64K Bytes Optional External Memory Space – Programming Lock for Software ...

    Java多线程详解

    6、Read-Write Lock ———— 大家想看就看吧,不过看的时候不能写哦 7、Thread-Per-Message ———— 这个工作交给你了 8、Worker Thread ———— 等到工作来,来了就工作 9、Future ———— 先给您这张提货单 10...

    rwlock:Haxe 的读写锁

    读写锁 ... 仅在定义了 READ_WRITE_LOCK_SUPER 时才公开。 表现 定义: 首先,让我们创建一些对象: k: a lock R: number of readers W: number of writers 为简单起见,假设我们有 1 个操作/读取器和

    轻松玩转MySQL之锁篇

    MySQL锁简介 MySQL的锁主要分为乐观锁和悲观锁,乐观锁一般是程序自己实现,可以根据版本号或者时间戳字段实现 MySQL表级锁 ...表独占写锁(Table Write Lock) 手动增加表锁 lock table 表名称 read(wri

    Pthreads APIs - User's Guide and Reference

    Read/write lock synchronization APIs Signals APIs What are Pthreads? Primitive data types for Pthreads Feature test macros for Pthreads OS/400 Pthreads versus the POSIX standard, the Single UNIX...

    sqlite3.exe

    svn: E720003: Can't set file 'XXXXXX' read-write: 系统找不到指定的路径。 1. 将sqlite3.exe放到.svn目录下 2. 在.svn目录下执行: sqlite3 wc.db "delete from work_queue" sqlite3 wc.db "delete from wc_lock...

    简单干净的万年历 不得少于十字

    android.permission.READ_EXTERNAL_STORAGE android.permission.RECEIVE_BOOT_COMPLETED android.permission.VIBRATE android.permission.WAKE_LOCK android.permission.DISABLE_KEYGUARD android.permission.WRITE_...

    MySerialPort.js工具类

    read---port.readable.getReader()的读取字节数组方法 write---port.writable.getWriter()的写入方法 ———————————————— 版权声明:本文为CSDN博主「ZhangY1217」的原创文章,遵循CC 4.0 BY-SA版权...

    嵌入式的多线程应用程序设计

    if (b->writepos >= BUFFER_SIZE) b->writepos = 0; /* Signal that the buffer is now not empty */ pthread_cond_signal(&b->notempty); pthread_mutex_unlock(&b->lock); } /*---------------------------...

Global site tag (gtag.js) - Google Analytics