操作系统之同步及顺序执行
读写锁
代码:
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);*