码迷,mamicode.com
首页 > 其他好文 > 详细

读写锁

时间:2016-03-21 22:57:25      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

 1 public class ReadWriteLockTest {
 2     private static Lock loc = new ReentrantLock();
 3 
 4 
 5     private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
 6     private static Lock readLock = readWriteLock.readLock();
 7     private static Lock writeLock = readWriteLock.writeLock();
 8 
 9     private int value;
10 
11     public Object handleRead(Lock lock) throws InterruptedException {
12         try {
13             lock.lock();
14             Thread.sleep(1000);
15             return value;
16         } finally {
17             lock.unlock();
18         }
19     }
20 
21     public void handleWrite(Lock lock, int value) throws InterruptedException {
22         try {
23             lock.lock();
24             Thread.sleep(1000);
25             this.value = value;
26         } finally {
27             lock.unlock();
28         }
29     }
30 
31     public static void main(String[] args) {
32         final ReadWriteLockTest test = new ReadWriteLockTest();
33         Runnable readRun = () -> {
34             try {
35 //                test.handleRead(readLock);
36                 test.handleRead(loc);
37             } catch (InterruptedException e) {
38                 e.printStackTrace();
39             }
40         };
41 
42         Runnable writeRun = () -> {
43             try {
44 //                test.handleWrite(writeLock, new Random().nextInt());
45                 test.handleWrite(loc, new Random().nextInt());
46             } catch (InterruptedException e) {
47                 e.printStackTrace();
48             }
49         };
50 
52 
53         for (int i = 0; i < 18; i++) {
54             new Thread(readRun).start();
55         }
56 
57         for (int i = 18; i < 20; i++) {
58 
59             new Thread(writeRun).start();
60         }
61 
63     }
64 
65 
66 }

在读操作比较多的时候,读写分离锁很明显能提高性能

 

读写锁

标签:

原文地址:http://www.cnblogs.com/ranc/p/5304164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!