0%

Java锁

公平锁和非公平锁

image-20200702165221917

image-20200702165423745

image-20200702165646193

可重入锁

image-20200702194111457

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
/**
* @author xixing
* @version 1.0
* @date 2020/7/2 19:16
*/
public class ReenterLockDemo {

public static void main(String[] args) {

Phone phone=new Phone();

new Thread(()->{
phone.sendMSG();
},"t1").start();
new Thread(()->{
phone.sendMSG();
},"t2").start();

Thread t3=new Thread(phone);
Thread t4=new Thread(phone);
t3.start();
t4.start();

}
}

class Phone implements Runnable{

public synchronized void sendMSG(){
System.out.println(Thread.currentThread().getId()+"\t invoked sendMSG()");
call();
}

public synchronized void call(){
//sendMSG();
System.out.println(Thread.currentThread().getId()+"\t invoked call()");
}

Lock lock=new ReentrantLock();

@Override
public void run() {
get();
}

public void get(){
//lock.lock();
lock.lock();
try {
System.out.println(Thread.currentThread().getId()+"\t get()");
set();

}finally {
lock.unlock();
//lock.unlock();
}

}
public void set(){
lock.lock();
try {
System.out.println(Thread.currentThread().getId()+"\t set()");
}finally {
lock.unlock();
}
}
}

读写锁

多个线程同时读一个资源类没有任何问题,所以为了满足并发量,读取公共资源应该可以同时进行

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
/**
* @author xixing
* @version 1.0
* @date 2020/7/2 20:21
* 多个线程同时读一个资源类没有任何问题,所以为了满足并发量,读取公共资源应该可以同时进行
* 如果有一个资源想要去写这个资源,那么其他资源就不可以对其进行读或者写
*
*
*/
public class ReadWriteLockDemo {
public static void main(String[] args) {

MyCache myCache=new MyCache();
for(int i=0;i<10;i++){
final int tempInt=i;
new Thread(()->{
myCache.setCache(String.valueOf(tempInt),String.valueOf(tempInt));
},String.valueOf(i)).start();
}
for(int i=0;i<10;i++){
final int tempInt=i;
new Thread(()->{
myCache.getCache(String.valueOf(tempInt));
},String.valueOf(i)).start();
}

}
}


class MyCache{//资源类

private volatile Map<String,Object> map=new HashMap<>();


ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock();


public void setCache(String key,Object value){
reentrantReadWriteLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName()+"\t cache"+key+"正在写入!!");
map.put(key,value);
System.out.println(Thread.currentThread().getName()+"\t cache"+key+"写入完成!!");
}finally {
reentrantReadWriteLock.writeLock().unlock();
}


}

public void getCache(String key){
reentrantReadWriteLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()+"\t cache正在读取!!");
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+"\t 读取完成!!cache="+o);

}finally {
reentrantReadWriteLock.readLock().unlock();
}
}

public void clear(){
map.clear();
}

}