File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
springboot-redisson-sample/src/main/java/com/ipman/springboot/redisson/sample/examples Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 77import javax .annotation .Resource ;
88import java .util .Map ;
99import java .util .Set ;
10+ import java .util .concurrent .CountDownLatch ;
1011
1112/**
1213 * Created by ipipman on 2021/1/28.
@@ -108,6 +109,45 @@ public void map() {
108109 System .out .println ("Map async put:" + futurePut .get ());
109110 System .out .println ("Map async get:" + futureGet .get ());
110111
112+
113+ // Map 对象锁,先获取锁,才能操作 Map 集合
114+ String k = "mapLock" ;
115+ for (int i = 0 ; i < 3 ; i ++) {
116+ Thread t = new Thread (() -> {
117+ RLock keyLock = map .getLock (k );
118+ keyLock .lock ();
119+ try {
120+ String v = map .get ("ipman" );
121+ System .out .println ("Map lock get:" + v + " t:" + Thread .currentThread ().getName ());
122+ // 其他业务逻辑
123+ } finally {
124+ keyLock .unlock ();
125+ }
126+ });
127+ t .setName ("thread-" + i );
128+ t .start ();
129+ }
130+
131+ // Map 读写锁,读时不能写
132+ for (int i = 0 ; i < 3 ; i ++) {
133+ Thread t = new Thread (() -> {
134+ RReadWriteLock rwLock = map .getReadWriteLock (k );
135+ rwLock .readLock ().lock ();
136+ try {
137+ String v = map .get ("ipman" );
138+ System .out .println ("Map read write lock get:" + v + " t:" + Thread .currentThread ().getName ());
139+ // 其他业务逻辑
140+ } finally {
141+ rwLock .readLock ().unlock ();
142+ }
143+ });
144+ t .setName ("thread-" + i );
145+ t .start ();
146+ }
147+
148+ // 阻塞等待
149+ System .in .read ();
150+
111151 }
112152
113153
You can’t perform that action at this time.
0 commit comments