0%

1.synchronized属于jvm层面的,属于java关键字,Lock是属于api层

底层汇编中synchronized由

monitorenter(底层是通过monitor对象来完成,其实wait/notify等方法也依赖monitor对象,只有在同步块或方法中才可以调用wait/notify等方法)

monitorexit两部分构成

Lock是具体类(java.util.concurrent.locks.Lock)是api层面的锁

2.使用方法

​ synchronized不需要用户手动释放锁,当synchronized代码执行完系统会自动让线程释放对锁的占用

​ ReentrantLock则需要用户去手动释放锁若没有主动释放锁,就有可能导致出现死锁现象。

3.等待是否可中断

​ synchronized不可中断,除非抛出异常或者正常运行完成

​ ReentrantLock可中断

​ 1.设置超时方法tryLock(long timeout,TimeUnit unit)

​ 2.lockInterruptibly()放代码块中,调用interrupt()方法

4.加锁是否公平

​ synchronized非公平锁

​ ReentrantLock两者都行

5.锁绑定多个条件condition

​ synchronized没有

​ ReentrantLock用来实现分组唤醒需要唤醒的线程们,可以精确唤醒,而不是像synchronized要么唤醒随机一个,要么唤醒全部。

image-20200703171101618

image-20200703171521954

image-20200703172044131

image-20200703191752807

image-20200703193418603

生产者消费者模式传统版

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
/**
* @author xixing
* @version 1.0
* @date 2020/7/3 19:57
*/
public class ProdConsumeTranditionalDemo {

public static void main(String[] args) {

ShareData shareData=new ShareData();
for(int i=0;i<10;i++){
new Thread(()->{
shareData.increment();
System.out.println(Thread.currentThread().getName()+"\t 生产成功!");
},String.valueOf(i)).start();
}
for(int i=0;i<10;i++){
new Thread(()->{
shareData.decrement();
System.out.println(Thread.currentThread().getName()+"\t 消费成功!");
},String.valueOf(i)).start();
}

}
}

class ShareData{
private Integer num=0;
private Lock lock=new ReentrantLock();
private Condition condition=lock.newCondition();

public void increment(){
lock.lock();
try{
while (num!=0){//不能用if,防止虚假唤醒
condition.await();
}
num++;
System.out.println(Thread.currentThread().getName()+"\t"+num);
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
lock.unlock();
}
}
public void decrement(){
lock.lock();
try{
while (num==0){
condition.await();
}
num--;
System.out.println(Thread.currentThread().getName()+"\t"+num);
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
lock.unlock();
}
}
}

Java右移操作,<<是有符号右移,如果是负数最左边补1

<<<是无符号右移,最左边默认补0

公平锁和非公平锁

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();
}

}

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

public void changeValue1(int num){
num=1000;
}

public void changeValue2(Person person){
person.setName("xxx");
}

public void changeValue3(String str){
str="xxx";
}

public static void main(String[] args) {
TestTransverValue test=new TestTransverValue();
int num=20;
test.changeValue1(num);
System.out.println("num========"+num);
Person person=new Person("abc");
test.changeValue2(person);
System.out.println("personName======"+person.getName());
String str="abc";
test.changeValue3(str);
System.out.println("str===="+str);
}
}

class Person{
public String name;

public Person(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}