Lock
1 | package cn.itcast.heima2; |
读写锁
Lock比Synchronized方式更加面向对象,而且锁本身也是一个对象,两个线程要实现同步互斥的效果,他们必须使用同一个lock对象
读写锁:多个读锁不互斥,读锁和写锁互斥,写锁和写锁互斥。这是由jvm控制的,你只要上相应的锁即可。如果你的代码只读数据,可以很多人读,但不能同时写那就上读锁;如果你的代码修改数据,只能有一个人在写,且不能同时读取,那就上写锁。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
66package cn.itcast.heima2;
import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockTest {
public static void main(String[] args) {
final Queue3 q3 = new Queue3();
for(int i=0;i<3;i++)
{
new Thread(){
public void run(){
while(true){
q3.get();
}
}
}.start();
new Thread(){
public void run(){
while(true){
q3.put(new Random().nextInt(10000));
}
}
}.start();
}
}
}
class Queue3{
private Object data = null;//共享数据,只有一个线程能写该数据,但是多个线程能同时读
ReadWriteLock rwl = new ReentrantReadWriteLock(); //todo 不能上普通的锁,否则读和写都会互斥
public void get(){
rwl.readLock().lock();//todo
try {
System.out.println(Thread.currentThread().getName() + " be ready to read data!");
Thread.sleep((long)(Math.random()*1000));
System.out.println(Thread.currentThread().getName() + "have read data :" + data);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
rwl.readLock().unlock(); //todo
}
}
public void put(Object data){
rwl.writeLock().lock(); //todo
try {
System.out.println(Thread.currentThread().getName() + " be ready to write data!");
Thread.sleep((long)(Math.random()*1000));
this.data = data;
System.out.println(Thread.currentThread().getName() + " have write data: " + data);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
rwl.writeLock().unlock(); //todo
}
}
}
读写锁缓存demo
1 | package cn.itcast.heima2; |