Java并发编程六读写锁
1、读写互斥
public class Test {//true 为公平锁,false为重入锁
public static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public static Lock readLock = lock.readLock();
public static Lock writeLock = lock.writeLock();
public static void main(String [] args) throws InterruptedException {
ThreadJoinTest t1 = new ThreadJoinTest("李雷");
ThreadJoinTest t2 = new ThreadJoinTest("韩梅梅");
ThreadJoinTest t3 = new ThreadJoinTest("露西");
ThreadJoinTest t4 = new ThreadJoinTest("莉莉");
t1.start();
t2.start();
t4.start();
ThreadUtil.sleep(100);
t3.start();
System.out.println("Main thread is finished");
}
}
class ThreadJoinTest extends Thread{
public ThreadJoinTest(String name){
super(name);
}
@Override
public void run(){
if(this.getName() .equals("露西")){
Test.writeLock.lock();
}else{
Test.readLock.lock();
}
for(int i=0;i<3;i++){
System.out.println(this.getName() + ":" + DateUtil.formatTime(new Date()));
ThreadUtil.sleep(1000);
}
if(this.getName() .equals("露西")){
Test.writeLock.unlock();
}else {
Test.readLock.unlock();
}
}
}
执行结果 读的时候写无法操作,读读可以同时执行
韩梅梅:16:49:23
李雷:16:49:23
莉莉:16:49:23
韩梅梅:16:49:24
李雷:16:49:24
莉莉:16:49:24
韩梅梅:16:49:25
李雷:16:49:25
莉莉:16:49:25
露西:16:49:26
露西:16:49:27
露西:16:49:28
二 写写互斥
public class Test {
//true 为公平锁,false为重入锁
public static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public static Lock readLock = lock.readLock();
public static Lock writeLock = lock.writeLock();
public static void main(String [] args) throws InterruptedException {
ThreadJoinTest t1 = new ThreadJoinTest("李雷");
ThreadJoinTest t2 = new ThreadJoinTest("韩梅梅");
ThreadJoinTest t3 = new ThreadJoinTest("露西");
ThreadJoinTest t4 = new ThreadJoinTest("莉莉");
t1.start();
t2.start();
t4.start();
t3.start();
System.out.println("Main thread is finished");
}
}
class ThreadJoinTest extends Thread{
public ThreadJoinTest(String name){
super(name);
}
@Override
public void run(){
Test.writeLock.lock();
for(int i=0;i<3;i++){
System.out.println(this.getName() + ":" + DateUtil.formatTime(new Date()));
ThreadUtil.sleep(1000);
}
Test.writeLock.unlock();
}
}
执行结果 可以看到写与写无法同时进行
莉莉:16:59:03
莉莉:16:59:04
莉莉:16:59:05
露西:16:59:06
露西:16:59:07
露西:16:59:08
李雷:16:59:09
李雷:16:59:10
李雷:16:59:11
韩梅梅:16:59:12
韩梅梅:16:59:13
韩梅梅:16:59:14
以上是 Java并发编程六读写锁 的全部内容, 来源链接: utcz.com/z/515564.html