File tree Expand file tree Collapse file tree 2 files changed +78
-0
lines changed
app/src/main/java/com/zhxh/codeproj/multithread/lock Expand file tree Collapse file tree 2 files changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .zhxh .codeproj .multithread .lock ;
2
+
3
+ import java .util .Random ;
4
+ import java .util .concurrent .locks .*;
5
+
6
+ /*
7
+ Java中的Lock接口,比起synchronized,优势在哪里?
8
+
9
+ 如果需要实现一个高效的缓存,它允许多个用户读,但只允许一个用户写,以此来保持它的完整性,如何实现?
10
+ Lock接口最大的优势是为读和写分别提供了锁。
11
+ 读写锁ReadWriteLock拥有更加强大的功能,它可细分为读锁和解锁。
12
+ 读锁可以允许多个进行读操作的线程同时进入,但不允许写进程进入;写锁只允许一个写进程进入,在这期间任何进程都不能再进入。
13
+ (完全符合题目中允许多个用户读和一个用户写的条件) 要注意的是每个读写锁都有挂锁和解锁,
14
+ 最好将每一对挂锁和解锁操作都用try、finally来套入中间的代码,这样就会防止因异常的发生而造成死锁得情况。
15
+ */
16
+ public class ReadWriteLockTest {
17
+ public static void main (String [] args ) {
18
+ final TheData myData = new TheData (); //这是各线程的共享数据
19
+ for (int i = 0 ; i < 3 ; i ++) { //开启3个读线程
20
+ new Thread (new Runnable () {
21
+ @ Override
22
+ public void run () {
23
+ while (true ) {
24
+ myData .get ();
25
+ }
26
+ }
27
+ }).start ();
28
+ }
29
+ for (int i = 0 ; i < 3 ; i ++) { //开启3个写线程
30
+ new Thread (new Runnable () {
31
+ @ Override
32
+ public void run () {
33
+ while (true ) {
34
+ myData .put (new Random ().nextInt (10000 ));
35
+ }
36
+ }
37
+ }).start ();
38
+ }
39
+ }
40
+ }
41
+
Original file line number Diff line number Diff line change
1
+ package com .zhxh .codeproj .multithread .lock ;
2
+
3
+ import java .util .Random ;
4
+ import java .util .concurrent .locks .ReadWriteLock ;
5
+ import java .util .concurrent .locks .ReentrantReadWriteLock ;
6
+
7
+ class TheData {
8
+ private Object data = null ;
9
+ private ReadWriteLock rwl = new ReentrantReadWriteLock ();
10
+
11
+ public void get () {
12
+ rwl .readLock ().lock (); //读锁开启,读线程均可进入
13
+ try { //用try finally来防止因异常而造成的死锁
14
+ System .out .println (Thread .currentThread ().getName () + " 正准备读" );
15
+ Thread .sleep (new Random ().nextInt (100 ));
16
+ System .out .println (Thread .currentThread ().getName () + " 已经读取到数据 " + data );
17
+ } catch (InterruptedException e ) {
18
+ e .printStackTrace ();
19
+ } finally {
20
+ rwl .readLock ().unlock (); //读锁解锁
21
+ }
22
+ }
23
+
24
+ public void put (Object data ) {
25
+ rwl .writeLock ().lock (); //写锁开启,这时只有一个写线程进入
26
+ try {
27
+ System .out .println (Thread .currentThread ().getName () + " 正准备读" );
28
+ Thread .sleep (new Random ().nextInt (100 ));
29
+ this .data = data ;
30
+ System .out .println (Thread .currentThread ().getName () + " 已经读取到数据 " + data );
31
+ } catch (InterruptedException e ) {
32
+ e .printStackTrace ();
33
+ } finally {
34
+ rwl .writeLock ().unlock (); //写锁解锁
35
+ }
36
+ }
37
+ }
You can’t perform that action at this time.
0 commit comments