ReadWriteLock rwl = new ReentrantReadWriteLock();读写锁
转载
class CachedData {
Object data;
volatile boolean cacheValid;
ReadWriteLock rwl = new ReentrantReadWriteLock();
void processCachedData() {
rwl.readLock().lock();
if (!cacheValid) {
// Must release read lock before acquiring write lock
rwl.readLock().unlock();
rwl.writeLock().lock();
// Recheck state because another thread might have acquired
// write lock and changed state before we did.
if (!cacheValid) {
data = ...
cacheValid = true;
}
// Downgrade by acquiring read lock before releasing write lock
rwl.writeLock().unlock(); // Unlock write, still hold read
rwl.readLock().lock();
//***************************************************
对象的方法中一旦加入synchronized修饰,则任何时刻只能有一个线程访问synchronized修饰的方法。假设有个数据对象拥有写方法与读方法,多线程环境中要想保证数据的安全,需对该对象的读写方法都要加入 synchronized同步块。这样任何线程在写入时,其它线程无法读取与改变数据;如果有线程在读取时,其他线程也无法读取或写入。这种方式在写入操作远大于读操作时,问题不大,而当读取远远大于写入时,会造成性能瓶颈,因为此种情况下读取操作是可以同时进行的,而加锁操作限制了数据的并发读取。
ReadWriteLock解决了这个问题,当写操作时,其他线程无法读取或写入数据,而当读操作时,其它线程无法写入数据,但却可以读取数据 。
且看 以下例子
1. public class
2. static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3.
4. public static void
5. new
6. new Worker(data,true);
7. new Worker(data,true);
8. t1.start();
9. t2.start();
10. }
11.
12. static class Worker extends
13. Data data;
14. boolean
15.
16. public Worker(Data data, boolean
17. this.data = data;
18. this.read = read;
19. }
20.
21. public void
22. if
23. data.get();
24. else
25. data.set();
26. }
27. }
28.
29. static class
30. new
31. Lock read = lock.readLock();
32. Lock write = lock.writeLock();
33. public void
34. write.lock();
35. System.out.println(Thread.currentThread().hashCode()
36. " set:begin " + sdf.format(new
37. try
38. 5000);
39. //
40. catch
41.
42. finally
43. " set:end "
44. new
45. write.unlock();
46. }
47.
48.
49. }
50.
51. public int
52. read.lock();
53. System.out.println(Thread.currentThread().hashCode()
54. " get :begin " + sdf.format(new
55. try
56. 5000);
57. //
58. catch
59.
60. finally
61. " get :end "
62. new
63. read.unlock();
64. }
65.
66.
67. return 1;
68. }
69. }
70. }
两个线程均是读线程,结果如下
22474382 get :begin 2011-04-16 18:26:13
4699264 get :begin 2011-04-16 18:26:13
22474382 get :end 2011-04-16 18:26:18
4699264 get :end 2011-04-16 18:26:18
两读线程均可同时读取数据,下面看一个是读线程,一个写线程的情况
Data data = new Data();
Worker t1 = new Worker(data,false);
Worker t2 = new Worker(data,true);
t2.start();
Thread.sleep(100);
t1.start();
先启动读取线程,再启动写入线程,看结果
14718739 get :begin 2011-04-16 18:54:46
14718739 get :end 2011-04-16 18:54:51
14737862 set:begin 2011-04-16 18:54:51
14737862 set:end 2011-04-16 18:54:56
可以看到读取线程工作时,写入线程是不能访问数据的