Skip to content

Commit 3bea44a

Browse files
committed
ReadWriteLockDemo
1 parent bbc293a commit 3bea44a

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package chapter3;
2+
3+
import java.util.Random;
4+
import java.util.concurrent.locks.Lock;
5+
import java.util.concurrent.locks.ReentrantLock;
6+
import java.util.concurrent.locks.ReentrantReadWriteLock;
7+
8+
/**
9+
* Created by 13 on 2017/5/5.
10+
*/
11+
public class ReadWriteLockDemo {
12+
private static Lock lock = new ReentrantLock();
13+
private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
14+
private static Lock readLock = reentrantReadWriteLock.readLock();
15+
private static Lock writeLock = reentrantReadWriteLock.writeLock();
16+
private int value;
17+
18+
public Object handleRead(Lock lock) throws InterruptedException {
19+
try {
20+
lock.lock();
21+
Thread.sleep(1000);//模拟读操作
22+
System.out.println("读操作:" + value);
23+
return value;
24+
} finally {
25+
lock.unlock();
26+
}
27+
}
28+
29+
public void handleWrite(Lock lock, int index) throws InterruptedException {
30+
try {
31+
lock.lock();
32+
Thread.sleep(1000);//模拟写操作
33+
System.out.println("写操作:" + value);
34+
value = index;
35+
} finally {
36+
lock.unlock();
37+
}
38+
}
39+
40+
public static void main(String args[]) {
41+
final ReadWriteLockDemo demo = new ReadWriteLockDemo();
42+
43+
Runnable readRunnable = new Runnable() {
44+
@Override
45+
public void run() {
46+
//分别使用两种锁来运行,性能差别很直观的就体现出来,使用读写锁后读操作可以并行,节省了大量时间
47+
try {
48+
demo.handleRead(readLock);
49+
//demo.handleRead(lock);
50+
} catch (InterruptedException e) {
51+
e.printStackTrace();
52+
}
53+
54+
}
55+
};
56+
57+
Runnable writeRunnable = new Runnable() {
58+
@Override
59+
public void run() {
60+
//分别使用两种锁来运行,性能差别很直观的就体现出来
61+
try {
62+
demo.handleWrite(writeLock, new Random().nextInt(100));
63+
//demo.handleWrite(lock, new Random().nextInt(100));
64+
} catch (InterruptedException e) {
65+
e.printStackTrace();
66+
}
67+
68+
}
69+
};
70+
for (int i = 0; i < 18; i++) {
71+
new Thread(readRunnable).start();
72+
}
73+
for (int i = 18; i < 20; i++) {
74+
new Thread(writeRunnable).start();
75+
}
76+
}
77+
}

0 commit comments

Comments
 (0)