Java多线程系列--“JUC锁”08之 共享锁和ReentrantReadWriteLock(五)

2014-11-24 02:55:45 · 作者: · 浏览: 9
的源码如下:
final boolean readerShouldBlock() {
return hasQueuedPredecessors();
}
在公平共享锁中,如果在当前线程的前面有其他线程在等待获取共享锁,则返回true;否则,返回false。
非公平锁的readerShouldBlock()的源码如下:
final boolean readerShouldBlock() {
return apparentlyFirstQueuedIsExclusive();
}
在非公平共享锁中,它会无视当前线程的前面是否有其他线程在等待获取共享锁。只要该非公平共享锁对应的线程不为null,则返回true。
ReentrantReadWriteLock示例
复制代码
1 import java.util.concurrent.locks.ReadWriteLock;
2 import java.util.concurrent.locks.ReentrantReadWriteLock;
3
4 public class ReadWriteLockTest1 {
5
6 public static void main(String[] args) {
7 // 创建账户
8 MyCount myCount = new MyCount("4238920615242830", 10000);
9 // 创建用户,并指定账户
10 User user = new User("Tommy", myCount);
11
12 // 分别启动3个“读取账户金钱”的线程 和 3个“设置账户金钱”的线程
13 for (int i=0; i<3; i++) {
14 user.getCash();
15 user.setCash((i+1)*1000);
16 }
17 }
18 }
19
20 class User {
21 private String name; //用户名
22 private MyCount myCount; //所要操作的账户
23 private ReadWriteLock myLock; //执行操作所需的锁对象
24
25 User(String name, MyCount myCount) {
26 this.name = name;
27 this.myCount = myCount;
28 this.myLock = new ReentrantReadWriteLock();
29 }
30
31 public void getCash() {
32 new Thread() {
33 public void run() {
34 myLock.readLock().lock();
35 try {
36 System.out.println(Thread.currentThread().getName() +" getCash start");
37 myCount.getCash();
38 Thread.sleep(1);
39 System.out.println(Thread.currentThread().getName() +" getCash end");
40 } catch (InterruptedException e) {
41 } finally {
42 myLock.readLock().unlock();
43 }
44 }
45 }.start();
46 }
47
48 public void setCash(final int cash) {
49 new Thread() {
50 public void run() {
51 myLock.writeLock().lock();
52 try {
53 System.out.println(Thread.currentThread().getName() +" setCash start");
54 myCount.setCash(cash);
55 Thread.sleep(1);
56 System.out.println(Thread.currentThread().getName() +" setCash end");
57 } catch (InterruptedException e) {
58 } finally {
59 myLock.writeLock().unlock();
60 }
61 }
62 }.start();
63 }
64 }
65
66 class MyCount {
67 private String id; //账号
68 private int cash; //账户余额
69
70 MyCount(String id, int cash) {
71 this.id = id;
72 this.cash = cash;
73 }
74
75 public String getId() {
76 return id;
77 }
78
79 public void setId(String id) {
80 this.id = id;
81 }
82
83 public int getCash() {
84 System.out.println(Thread.currentThread().getName() +" getCash cash="+ cash);
85 return cash;
86 }
87
88 public void setCash(int cash) {
89 System.out.println(Thread.currentThread().getName() +" setCash cash="+ cash);
90 this.cash = cash;
91 }
92 }
复制代码
运行结果:
复制代码
Thread-0 getCash start
Thread-2 getCash start
Thread-0 getCash cash=10000