-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadWriteLockDemo.java
More file actions
92 lines (74 loc) · 2.52 KB
/
Copy pathReadWriteLockDemo.java
File metadata and controls
92 lines (74 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package readwrite;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author : CodeWater
* @create :2022-06-03-18:02
* @Function Description :演示读写锁
*/
class MyCache {
//创建map集合
private volatile Map<String , Object> map = new HashMap<>();
//创建读写锁对象
private ReadWriteLock rwLock = new ReentrantReadWriteLock();
//放数据
public void put( String key , Object value ){
//添加写锁
rwLock.writeLock().lock();
try{
System.out.println(Thread.currentThread().getName()+" 正在写操作"+key);
//暂停一会(千分之一毫秒)
TimeUnit.MICROSECONDS.sleep( 300 );
//放数据
map.put( key , value );
System.out.println(Thread.currentThread().getName()+" 写完了"+key);
}catch( InterruptedException e ){
e.printStackTrace();
}finally{
//释放写锁
rwLock.writeLock().unlock();
}
}
//取数据
public Object get( String key ){
//添加读锁
rwLock.readLock().lock();
Object result = null;
try{
System.out.println(Thread.currentThread().getName()+" 正在读取操作"+key);
//暂停一会
TimeUnit.MICROSECONDS.sleep( 300 );
result = map.get( key );
System.out.println(Thread.currentThread().getName()+" 取完了"+key);
}catch ( InterruptedException e ){
e.printStackTrace();
}finally{
//释放读锁
rwLock.readLock().unlock();
}
return result;
}
}
public class ReadWriteLockDemo {
public static void main( String[] args) throws InterruptedException {
MyCache myCache = new MyCache();
//创建线程放数据
for( int i = 1 ; i <= 5 ; i++ ){
final int num = i;
new Thread( () -> {
myCache.put( num + "" , num + "" );
} , String.valueOf( i ) ).start();
}
TimeUnit.MICROSECONDS.sleep( 300 );
//创建线程取数据
for( int i = 1 ; i <= 5 ; i++ ){
final int num = i ;
new Thread( () -> {
myCache.get( num + "" );
} , String.valueOf( i ) ).start();
}
}
}