0%

Juc

线程和进程

进程是操作系统中的应用程序,是资源分配的基本单位,线程是用来执行具体的任务和功能,是CPU调度和分派的最小单位。

一个进程往往可以包含多个线程,至少包含一个。

对于Java而言:Thread、Runable、Callable进行开启线程的。

什么是JUC

Runnable 没有返回值,企业中使用Callable

java默认有几个线程?

java默认有两个线程:main、GC

java真的可以开启线程吗?

不可以!

1
2
3
4
5
6
7
8
9
package com.guocl.demo0;

public class Test0 {
public static void main(String[] args) {
//查看线程启动,点击start查看
new Thread().start();
}
}

1
2
3
//java源码:调用native方法(本地方法栈的C++方法),java运行在虚拟机之上,无法直接操作硬件,由C++开启多线程。
private native void start0();

并发编程:并发、并行;

并发(多线程操作同一资源)

  • CPU一核,模拟出来多条线程,快速交替。

并行(多个人一起行走)

  • CPU多核,多个线程可以同时执行;线程池。

并发编程的本质:充分利用cpu资源

使用代码查看cpu

1
2
3
4
5
6
7
8
9
10
package com.guocl.demo0;

public class Test0 {
public static void main(String[] args) {
//获取cpu的核数
//cpu密集型,io密集型
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
//结果为 4

线程的状态

1
2
3
4
5
6
7
8
9
package com.guocl.demo0;

public class Test0 {
public static void main(String[] args) {
//查看线程状态,恩住ctrl,点State
Thread.State
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//线程的状态:6个
public enum State {
//就绪
NEW,
//运行
RUNNABLE,
//阻塞
BLOCKED,
//等待(死死的等)
WAITING,
//超时等待(超过一定时间,不再等待)
TIMED_WAITING,
//终止
TERMINATED;
}

wait于sleep的区别

来自不同的类
wait=》Object
sleep=》Thread
wait释放锁,sleep不释放锁(sleep抱着锁睡觉)
wait必须在同步代码块中,sleep可以在任何地方(sleep可以在任何地方睡觉)
wait不需要捕获异常,sleep需要捕获异常(可能发生超时等待)

Lock锁(重点)

传统的Synchronized锁

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
package com.guocl.demo0;

/**
* 不加Synchronized
* 真正的多线程开发
* 线程就是一个资源类,没有任何附属的操作
*/
public class SaleTicket {

public static void main(String[] args) {
//并发:多线程操作同一个资源类,把资源类丢入线程
Ticket ticket = new Ticket();
// Runnable方式 -- @FunctionalInterface函数式接口
// new Thread(new Runnable() {
// @Override
// public void run() {
//
// }
// }).start();
// jdk1.8 使用lambda表达式
new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}, "A").start();

new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}, "B").start();

new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}, "C").start();
}
}

//资源类OOP编程
class Ticket{
//属性,方法
private int number = 30;
//买票的方式
public void sale(){
if (number > 0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+(number--)+"票,剩余:"+number);
}
}

}

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
A卖出了第30票,剩余:29
B卖出了第29票,剩余:28
A卖出了第28票,剩余:27
B卖出了第27票,剩余:26
A卖出了第26票,剩余:25
B卖出了第25票,剩余:24
B卖出了第23票,剩余:22
B卖出了第22票,剩余:21
B卖出了第21票,剩余:20
B卖出了第20票,剩余:19
B卖出了第19票,剩余:18
B卖出了第18票,剩余:17
B卖出了第17票,剩余:16
B卖出了第16票,剩余:15
B卖出了第15票,剩余:14
B卖出了第14票,剩余:13
B卖出了第13票,剩余:12
B卖出了第12票,剩余:11
B卖出了第11票,剩余:10
B卖出了第10票,剩余:9
B卖出了第9票,剩余:8
B卖出了第8票,剩余:7
B卖出了第7票,剩余:6
B卖出了第6票,剩余:5
B卖出了第5票,剩余:4
B卖出了第4票,剩余:3
B卖出了第3票,剩余:2
B卖出了第2票,剩余:1
B卖出了第1票,剩余:0
A卖出了第24票,剩余:23

Process finished with exit code 0
//结果是乱的
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
package com.guocl.demo0;

/**
* 不加Synchronized
* 真正的多线程开发
* 线程就是一个资源类,没有任何附属的操作
*/
public class SaleTicket {

public static void main(String[] args) {
//并发:多线程操作同一个资源类,把资源类丢入线程
Ticket ticket = new Ticket();
// Runnable方式 -- @FunctionalInterface函数式接口
// new Thread(new Runnable() {
// @Override
// public void run() {
//
// }
// }).start();
// jdk1.8 使用lambda表达式
new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}, "A").start();

new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}, "B").start();

new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}, "C").start();
}
}

//资源类OOP编程
class Ticket{
//属性,方法
private int number = 30;
//买票的方式
//synchronized 本质:队列,锁
public synchronized void sale(){
if (number > 0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+(number--)+"票,剩余:"+number);
}
}

}

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
A卖出了第30票,剩余:29
A卖出了第29票,剩余:28
A卖出了第28票,剩余:27
A卖出了第27票,剩余:26
A卖出了第26票,剩余:25
A卖出了第25票,剩余:24
A卖出了第24票,剩余:23
A卖出了第23票,剩余:22
A卖出了第22票,剩余:21
A卖出了第21票,剩余:20
A卖出了第20票,剩余:19
A卖出了第19票,剩余:18
A卖出了第18票,剩余:17
A卖出了第17票,剩余:16
A卖出了第16票,剩余:15
A卖出了第15票,剩余:14
A卖出了第14票,剩余:13
A卖出了第13票,剩余:12
A卖出了第12票,剩余:11
A卖出了第11票,剩余:10
A卖出了第10票,剩余:9
A卖出了第9票,剩余:8
A卖出了第8票,剩余:7
A卖出了第7票,剩余:6
A卖出了第6票,剩余:5
A卖出了第5票,剩余:4
A卖出了第4票,剩余:3
A卖出了第3票,剩余:2
A卖出了第2票,剩余:1
A卖出了第1票,剩余:0

Process finished with exit code 0


Lock锁(接口)1680096740590

  • 公平锁:十分公平,必须先来后到;
  • 非公平锁:十分不公平,可以插队; (默认为非公平锁)

用lock锁实现买票实例

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
package com.guocl.demo0;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTicket {
public static void main(String[] args) {
//资源类
Ticket2 ticket2 = new Ticket2();
new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket2.sale();
}
},"A").start();

new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket2.sale();
}
},"B").start();

new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket2.sale();
}
},"C").start();

}

}

//lock三部曲
//1、 Lock lock=new ReentrantLock();
//2、 lock.lock() 加锁
//3、 finally=> 解锁:lock.unlock();
class Ticket2{
//属性,方法
private int number = 30;
//创建锁
Lock lock = new ReentrantLock();
//买票的方式
public void sale(){
//开启锁
lock.lock();
try {
if (number > 0){
System.out.println(Thread.currentThread().getName()+"卖出了第"+(number--)+"票,剩余:"+number);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//释放锁
lock.unlock();
}
}
}

Synchronized和Lock区别

1、Synchronized 是内置的java关键字,Lock是一个接口;

2、Synchronized 无法判断获取锁的状态,Lock可以判断;

3、Synchronized 会自动释放锁,Lock必须要手动加锁和手动释放锁!(若不释放锁,可能会造成死锁);

4、Synchronized 线程1(获得锁->阻塞)、线程2(等待)(会一直等待下去);Lock就不一定会一直等待下去,lock会有一个trylock去尝试获取锁,不会造成长久的等待;

5、Synchronized 是可重入锁,不可以中断的,非公平锁;Lock是可重入锁,可以中断锁,可以自己设置公平锁和非公平锁;

6、Synchronized 适合锁少量的代码同步问题,Lock适合锁大量同步代码问题;

深入研究Lock和Synchronized的区别于用法

参考文章:

http://t.csdn.cn/Uouwa

1、synchronize和lock的用法区别

synchronize:在需要同步的对象中加入此控制,synchronize可以加在方法上(同步方法),也可以加在特定代码块中(同步代码块),括号中表示需要锁的对象。

lock:需要显示指定起始位置和终止位置。一般使用ReentranLock类做为锁,多个线程中必须要使用一个ReentranLock类做为对象才能保证锁的生效。且在加锁和解锁处需要通过lock()和unlock()显示指出。所以一般会在finally块中写unlock()以防死锁。

2、synchronized和lock性能区别

synchronized是托管给JVM执行的,而lock是java写的控制锁的代码。在Java1.5中,synchronized是性能很低效的。因为这是一个重量级操作。需要调用操作接口,导致有可能加锁消耗的系统时间比加锁以外的操作还多。相比之下使用java提供的lock对象,性能更高一些。但是到了JDK1.6,发生了变化。synchronize在语义上很清晰,可以进行很多优化,有适应自旋,锁消除,锁粗化,轻量级锁,偏向锁等等。导致在Java1.6上synchronize的性能并不比Lock差。官方也表示,他们也更支持synchronize,在未来的版本中还有优化余地。

说到这里,还是想提一下这两种机制的具体区别。据我所知,synchronized原始采用的是CPU悲观锁机制,即线程获得的是独占锁。独占锁意味着其他线程只能依靠阻塞来等待线程释放锁。而在CPU转换线程阻塞时会引起线程上下文切换,当有很多线程竞争锁的时候,会引起CPU频繁的上下文切换导致效率很低。

而lock用的是乐观锁方式,所谓乐观锁就是,每次不加锁而是假设没有冲突而去完成某项操作,如果因为冲突失败就重试,直到成功为止。乐观锁实现的机制就是CAS操作Compare and Swap)。我们可以进一步研究ReentrantLock的源代码,会发现其中比较重要的获得锁的一个方法是compareAndSetState。这里其实就是调用的CPU提供的特殊指令。

现代的CPU提供了指令,可以自动更新共享数据,而且能够检测其他线程的干扰,而 compareAndSet() 就用这些代替了锁定。这个算法称作非阻塞算法,意思是一个线程的失败或者挂起不应该影响其他线程的失败或挂起的算法。

3、synchronized和lock用途区别

synchronized原语和ReentrantLock在一般情况下没有什么区别,但是在非常复杂的同步应用中,请考虑使用ReentrantLock,特别是遇到下面2种需求的时候。

某个线程在等待一个锁的控制权的这段时间需要中断。
需要分开处理一些wait(等待)-notify(唤醒),ReentrantLock里面的Condition应用(Condition定义了等待await/通知signal、signalAll两种类型的方法),能够控制notify哪个线程。
具有公平锁功能,每个到来的线程都将排队等候。
下面细细道来……

先说第一种情况,ReentrantLock的lock机制有2种,忽略中断锁和响应中断锁,这给我们带来了很大的灵活性。比如:如果A、B2个线程去竞争锁,A线程得到了锁,B线程等待,但是A线程这个时候实在有太多事情要处理,就是一直不返回,B线程可能就会等不及了,想中断自己,不再等待这个锁了,转而处理其他事情。这个时候ReentrantLock就提供了2种机制,第一,B线程中断自己(或者别的线程中断它),但是ReentrantLock不去响应,继续让B线程等待,你再怎么中断,我全当耳边风(synchronized原语就是如此);第二,B线程中断自己(或者别的线程中断它),ReentrantLock处理了这个中断,并且不再等待这个锁的到来,完全放弃。(如果你没有了解java的中断机制,请参考下相关资料,再回头看这篇文章,80%的人根本没有真正理解什么是java的中断(下面有讲解),呵呵)

这里来做个试验,首先搞一个Buffer类,它有读操作和写操作,为了不读到脏数据,写和读都需要加锁,我们先用synchronized原语来加锁,如下:

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
package com.guocl.lockorsyn.syndemo;

public class Buffer {
private Object lock;

public Buffer(){
lock = this;
}

public void write(){
synchronized (lock){
long startTime = System.currentTimeMillis();
System.out.println("开始往这个buff写入数据…");
// 模拟要处理很长时间
for (;;){
if (System.currentTimeMillis() - startTime > Integer.MAX_VALUE)
break;
}
System.out.println("终于写完了");
}
}

public void read(){
synchronized (lock){
System.out.println("从这个buff读数据");
}
}


}

读操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.guocl.lockorsyn.syndemo;

public class Reader extends Thread{
private Buffer buffer;

public Reader(Buffer buffer){
this.buffer = buffer;
}

@Override
public void run() {
//这里估计会一直阻塞
buffer.read();
System.out.println("读结束");
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.guocl.lockorsyn.syndemo;

public class Writer extends Thread{
private Buffer buffer;

public Writer(Buffer buffer){
this.buffer = buffer;
}

@Override
public void run() {
buffer.write();
}
}

Main方法

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
package com.guocl.lockorsyn.syndemo;

public class Test {
public static void main(String[] args) {
Buffer buffer = new Buffer();

final Writer writer = new Writer(buffer);
final Reader reader = new Reader(buffer);

writer.start();
reader.start();

new Thread(() -> {
long start = System.currentTimeMillis();
for (;;){
//等5秒钟去中断读
if (System.currentTimeMillis() - start > 5000){
System.out.println("不等了,尝试中断");
reader.interrupt();
break;
}
}
}).start();

}
}

结果

1
2
3
开始往这个buff写入数据…
不等了,尝试中断

我们期待“读”这个线程能退出等待锁,可是事与愿违,一旦读这个线程发现自己得不到锁,就一直开始等待了,就算它等死,也得不到锁,因为写线程要21亿秒才能完成 T_T ,即使我们中断它,它都不来响应下,看来真的要等死了。

这个时候,ReentrantLock给了一种机制让我们来响应中断,让“读”能伸能屈,勇敢放弃对这个锁的等待。我们来改写Buffer这个类,就叫BufferInterruptibly吧,可中断缓存。

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
package com.guocl.lockorsyn.lockdemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class BufferInterruptibly{

private Lock lock = new ReentrantLock();

public void write(){
lock.lock();
try {
long startTime = System.currentTimeMillis();
System.out.println("开始往这个buff写入数据…");
for (;;)// 模拟要处理很长时间
{
if (System.currentTimeMillis()
- startTime > Integer.MAX_VALUE)
break;
}
System.out.println("终于写完了");
} finally {
lock.unlock();
}
}

public void read() throws InterruptedException {
// 注意这里,可以响应中断
lock.lockInterruptibly();
try {
System.out.println("从这个buff读数据");
} 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
package com.guocl.lockorsyn.lockdemo;

public class Reader extends Thread{

private BufferInterruptibly buff;

public Reader(BufferInterruptibly buff){
this.buff = buff;
}

@Override
public void run() {
try {
//可以收到中断的异常,从而有效退出
buff.read();
} catch (InterruptedException e) {
System.out.println("我不读了");
}
System.out.println("读结束");
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.guocl.lockorsyn.lockdemo;

public class Writer extends Thread{

private BufferInterruptibly buff;

public Writer(BufferInterruptibly buff){
this.buff = buff;
}

@Override
public void run() {
buff.write();
}
}

测试

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
package com.guocl.lockorsyn.lockdemo;

public class Test {

public static void main(String[] args) {
BufferInterruptibly buff = new BufferInterruptibly();

final Reader reader = new Reader(buff);
final Writer writer = new Writer(buff);

writer.start();
reader.start();

new Thread(()->{
long start = System.currentTimeMillis();
for (;;) {
if (System.currentTimeMillis()
- start > 5000) {
System.out.println("不等了,尝试中断");
reader.interrupt();
break;
}
}
}).start();
}
}

结果

1
2
3
4
5
开始往这个buff写入数据…
不等了,尝试中断
我不读了
读结束

这次“读”线程接收到了lock.lockInterruptibly()中断,并且有效处理了这个“异常”。

至于第二种情况,ReentrantLock可以与Condition的配合使用,Condition为ReentrantLock锁的等待和释放提供控制逻辑。
例如,使用ReentrantLock加锁之后,可以通过它自身的Condition.await()方法释放该锁,线程在此等待Condition.signal()方法,然后继续执行下去。await方法需要放在while循环中,因此,在不同线程之间实现并发控制,还需要一个volatile的变量,boolean是原子性的变量。因此,一般的并发控制的操作逻辑如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
volatile boolean isProcess = false;
ReentrantLock lock = new ReentrantLock();
Condtion processReady = lock.newCondtion();
thread: run() {
lock.lock();
isProcess = true;
try {
while(!isProcessReady) { //isProcessReady 是另外一个线程的控制变量
processReady.await();//释放了lock,在此等待signal
}catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
isProcess = false;
}
}
}
}

这里只是代码使用的一段简化,下面我们看Hadoop的一段摘取的源码:

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
	private class MapOutputBuffer<K extends Object, V extends Object>
2
implements MapOutputCollector<K, V>, IndexedSortable {
3
...
4
boolean spillInProgress;
5
final ReentrantLock spillLock = new ReentrantLock();
6
final Condition spillDone = spillLock.newCondition();
7
final Condition spillReady = spillLock.newCondition();
8
volatile boolean spillThreadRunning = false;
9
final SpillThread spillThread = new SpillThread();
10
...
11
public MapOutputBuffer(TaskUmbilicalProtocol umbilical, JobConf job,
12
TaskReporter reporter
13
) throws IOException, ClassNotFoundException {
14
...
15
spillInProgress = false;
16
spillThread.setDaemon(true);
17
spillThread.setName("SpillThread");
18
spillLock.lock();
19
try {
20
spillThread.start();
21
while (!spillThreadRunning) {
22
spillDone.await();
23
}
24
} catch (InterruptedException e) {
25
throw new IOException("Spill thread failed to initialize", e);
26
} finally {
27
spillLock.unlock();
28
}
29
}
30

31
protected class SpillThread extends Thread {
32

33
@Override
34
public void run() {
35
spillLock.lock();
36
spillThreadRunning = true;
37
try {
38
while (true) {
39
spillDone.signal();
40
while (!spillInProgress) {
41
spillReady.await();
42
}
43
try {
44
spillLock.unlock();
45
sortAndSpill();
46
} catch (Throwable t) {
47
sortSpillException = t;
48
} finally {
49
spillLock.lock();
50
if (bufend < bufstart) {
51
bufvoid = kvbuffer.length;
52
}
53
kvstart = kvend;
54
bufstart = bufend;
55
spillInProgress = false;
56
}
57
}
58
} catch (InterruptedException e) {
59
Thread.currentThread().interrupt();
60
} finally {
61
spillLock.unlock();
62
spillThreadRunning = false;
63
}
64
}
65
}

代码中spillDone 就是 spillLock的一个newCondition()。调用spillDone.await()时可以释放spillLock锁,线程进入阻塞状态,而等待其他线程的 spillDone.signal()操作时,就会唤醒线程,重新持有spillLock锁。

这里可以看出,利用lock可以使我们多线程交互变得方便,而使用synchronized则无法做到这点。

最后呢,ReentrantLock这个类还提供了2种竞争锁的机制:公平锁和非公平锁。这2种机制的意思从字面上也能了解个大概:即对于多线程来说,公平锁会依赖线程进来的顺序,后进来的线程后获得锁。而非公平锁的意思就是后进来的锁也可以和前边等待锁的线程同时竞争锁资源。对于效率来讲,当然是非公平锁效率更高,因为公平锁还要判断是不是线程队列的第一个才会让线程获得锁。

3.4、Java中断机制
参考文章:http://t.csdn.cn/sQxDN

3.4.1、中断
如果程序需要停止正在运行的线程,如果直接stop线程,则有可能导致程序运行不完整,因此Java提供了中断机制。中断(Interrupt)一个线程意味着在该线程完成任务之前停止其正在进行的一切,有效地终止其当前的操作。线程是死亡、还是等待新的任务或者是继续运行至下一步,就取决于这个程序。虽然初次看来它可能显得简单,但是,你必须进行一些预警以实现期望的结果。你最好还是牢记以下的几点告诫。

首先,忘掉Thread.stop方法。虽然它确实停止了一个正在运行的线程,然而,这种方法是不安全也是不受提倡的,这意味着,在未来的JAVA版本中,它将不复存在。
Java的中断是一种协作机制,也就是说通过中断并不能直接STOP另外一个线程,而需要被中断的线程自己处理中断,即仅给了另一个线程一个中断标识,由线程自行处理。
3.4.2、中断的原理
Java中断机制是一种协作机制,也就是说通过中断并不能直接终止另一个线程,而需要被中断的线程自己处理中断。这好比是家里的父母叮嘱在外的子女要注意身体,但子女是否注意身体,怎么注意身体则完全取决于自己。

Java中断模型也是这么简单,每个线程对象里都有一个boolean类型的标识(不一定就要是Thread类的字段,实际上也的确不是,这几个方法最终都是通过native方法来完成的),代表着是否有中断请求(该请求可以来自所有线程,包括被中断的线程本身)。例如,当线程t1想中断线程t2,只需要在线程t1中将线程t2对象的中断标识置为true,然后线程2可以选择在合适的时候处理该中断请求,甚至可以不理会该请求,就像这个线程没有被中断一样。

java.lang.Thread类提供了几个方法来操作这个中断状态,这些方法包括:

public static boolean interrupted
测试当前线程是否已经中断。线程的中断状态 由该方法清除。换句话说,如果连续两次调用该方法,则第二次调用将返回 false(在第一次调用已清除了其中断状态之后,且第二次调用检验完中断状态前,当前线程再次中断的情况除外)。

public boolean isInterrupted()
测试线程是否已经中断。线程的中断状态不受该方法的影响。

public void interrupt()
中断线程。

其中,interrupt方法是唯一能将中断状态设置为true的方法。静态方法interrupted会将当前线程的中断状态清除,但这个方法的命名极不直观,很容易造成误解,需要特别注意。

上面的例子中,线程t1通过调用interrupt方法将线程t2的中断状态置为true,t2可以在合适的时候调用interrupted或isInterrupted来检测状态并做相应的处理。

此外,类库中的有些类的方法也可能会调用中断,如FutureTask中的cancel方法,如果传入的参数为true,它将会在正在运行异步任务的线程上调用interrupt方法,如果正在执行的异步任务中的代码没有对中断做出响应,那么cancel方法中的参数将不会起到什么效果;又如ThreadPoolExecutor中的shutdownNow方法会遍历线程池中的工作线程并调用线程的interrupt方法来中断线程,所以如果工作线程中正在执行的任务没有对中断做出响应,任务将一直执行直到正常结束。

3.4.3、中断的处理
既然Java中断机制只是设置被中断线程的中断状态,那么被中断线程该做些什么?

3.4.3.1、处理时机
显然,作为一种协作机制,不会强求被中断线程一定要在某个点进行处理。实际上,被中断线程只需在合适的时候处理即可,如果没有合适的时间点,甚至可以不处理,这时候在任务处理层面,就跟没有调用中断方法一样。“合适的时候”与线程正在处理的业务逻辑紧密相关,例如,每次迭代的时候,进入一个可能阻塞且无法中断的方法之前等,但多半不会出现在某个临界区更新另一个对象状态的时候,因为这可能会导致对象处于不一致状态。

处理时机决定着程序的效率与中断响应的灵敏性。频繁的检查中断状态可能会使程序执行效率下降,相反,检查的较少可能使中断请求得不到及时响应。如果发出中断请求之后,被中断的线程继续执行一段时间不会给系统带来灾难,那么就可以将中断处理放到方便检查中断,同时又能从一定程度上保证响应灵敏度的地方。当程序的性能指标比较关键时,可能需要建立一个测试模型来分析最佳的中断检测点,以平衡性能和响应灵敏性。

3.4.3.2、处理方式
1、 中断状态的管理

一般说来,当可能阻塞的方法声明中有抛出InterruptedException则暗示该方法是可中断的,如BlockingQueue#put、BlockingQueue#take、Object#wait、Thread#sleep等,如果程序捕获到这些可中断的阻塞方法抛出的InterruptedException或检测到中断后,这些中断信息该如何处理?一般有以下两个通用原则:

如果遇到的是可中断的阻塞方法抛出InterruptedException,可以继续向方法调用栈的上层抛出该异常,如果是检测到中断,则可清除中断状态并抛出InterruptedException,使当前方法也成为一个可中断的方法。
若有时候不太方便在方法上抛出InterruptedException,比如要实现的某个接口中的方法签名上没有throws InterruptedException,这时就可以捕获可中断方法的InterruptedException并通过Thread.currentThread.interrupt()来重新设置中断状态。如果是检测并清除了中断状态,亦是如此。
一般的代码中,尤其是作为一个基础类库时,绝不应当吞掉中断,即捕获到InterruptedException后在catch里什么也不做,清除中断状态后又不重设中断状态也不抛出InterruptedException等。因为吞掉中断状态会导致方法调用栈的上层得不到这些信息。

当然,凡事总有例外的时候,当你完全清楚自己的方法会被谁调用,而调用者也不会因为中断被吞掉了而遇到麻烦,就可以这么做。

总得来说,就是要让方法调用栈的上层获知中断的发生。假设你写了一个类库,类库里有个方法amethod,在amethod中检测并清除了中断状态,而没有抛出InterruptedException,作为amethod的用户来说,他并不知道里面的细节,如果用户在调用amethod后也要使用中断来做些事情,那么在调用amethod之后他将永远也检测不到中断了,因为中断信息已经被amethod清除掉了。如果作为用户,遇到这样有问题的类库,又不能修改代码,那该怎么处理?只好在自己的类里设置一个自己的中断状态,在调用interrupt方法的时候,同时设置该状态,这实在是无路可走时才使用的方法。

2、中断的响应

程序里发现中断后该怎么响应?这就得视实际情况而定了。有些程序可能一检测到中断就立马将线程终止,有些可能是退出当前执行的任务,继续执行下一个任务……作为一种协作机制,这要与中断方协商好,当调用interrupt会发生些什么都是事先知道的,如做一些事务回滚操作,一些清理工作,一些补偿操作等。若不确定调用某个线程的interrupt后该线程会做出什么样的响应,那就不应当中断该线程。

3.4.3.3、线程在不同状态下对于中断所产生的反应
线程一共6种状态,分别是NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED(Thread类中有一个State枚举类型列举了线程的所有状态)。

NEW和TERMINATED
线程的new状态表示还未调用start方法,还未真正启动。线程的terminated状态表示线程已经运行终止。这两个状态下调用中断方法来中断线程的时候,Java认为毫无意义,所以并不会设置线程的中断标识位,什么事也不会发生。

RUNNABLE
如果线程处于运行状态,那么该线程的状态就是RUNNABLE,但是不一定所有处于RUNNABLE状态的线程都能获得CPU运行,在某个时间段,只能由一个线程占用CPU,那么其余的线程虽然状态是RUNNABLE,但是都没有处于运行状态。而我们处于RUNNABLE状态的线程在遭遇中断操作的时候只会设置该线程的中断标志位,并不会让线程实际中断,想要发现本线程已经被要求中断了则需要用程序去判断。

BLOCKED
当线程处于BLOCKED状态说明该线程由于竞争某个对象的锁失败而被挂在了该对象的阻塞队列上了。那么此时发起中断操作不会对该线程产生任何影响,依然只是设置中断标志位。

WAITING/TIMED_WAITING
这两种状态本质上是同一种状态,只不过TIMED_WAITING在等待一段时间后会自动释放自己,而WAITING则是无限期等待,需要其他线程调用notify方法释放自己。但是他们都是线程在运行的过程中由于缺少某些条件(例如:调用wait())而被挂起在某个对象的等待队列上。当这些线程遇到中断操作的时候,会抛出一个InterruptedException异常,并清空中断标志位。

Thread.interrupt VS Thread.stop

Thread.stop方法已经不推荐使用了。而在某些方面Thread.stop与中断机制有着相似之处。如当线程在等待内置锁或IO时,stop跟interrupt一样,不会中止这些操作;当catch住stop导致的异常时,程序也可以继续执行,虽然stop本意是要停止线程,这么做会让程序行为变得更加混乱。

那么它们的区别在哪里?最重要的就是中断需要程序自己去检测然后做相应的处理,而Thread.stop会直接在代码执行过程中抛出ThreadDeath错误,这是一个java.lang.Error的子类。

3.4.4、使用 interrupt 方法
Thread.interrupt()方法: 作用是中断线程。将会设置该线程的中断状态位,即设置为true,中断的结果线程是死亡、还是等待新的任务或是继续运行至下一步,就取决于这个程序本身。线程会不时地检测这个中断标示位,以判断线程是否应该被中断(中断标示值是否为true)。它并不像stop方法那样会中断一个正在运行的线程。

interrupt()方法只是改变中断状态,不会中断一个正在运行的线程。需要用户自己去监视线程的状态为并做处理。支持线程中断的方法(也就是线程中断后会抛出interruptedException的方法)就是在监视线程的中断状态,一旦线程的中断状态被置为“中断状态”,就会抛出中断异常。这一方法实际完成的是,给受阻塞的线程发出一个中断信号,这样受阻线程检查到中断标识,就得以退出阻塞的状态。

更确切的说,如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞,此时调用该线程的interrupt()方法,那么该线程将抛出一个 InterruptedException中断异常(该线程必须事先预备好处理此异常),从而提早地终结被阻塞状态。如果线程没有被阻塞,这时调用 interrupt()将不起作用,直到执行到wait(),sleep(),join()时,才马上会抛出 InterruptedException。

3.4.4.1、使用 interrupt() + InterruptedException来中断线程
线程处于阻塞状态,如Thread.sleep、wait、IO阻塞等情况时,调用interrupt方法后,sleep等方法将会抛出一个InterruptedException:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args) {
Thread thread = new Thread() {
public void run() {
System.out.println("线程启动了");
try {
Thread.sleep(1000 * 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程结束了");
}
};
thread.start();

try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();//作用是:在线程阻塞时抛出一个中断信号,这样线程就得以退出阻塞的状态
}

使用 interrupt() + isInterrupted()来中断线程
this.interrupted()😗测试当前线程是否已经中断(静态方法)。如果连续调用该方法,则第二次调用将返回false。在api文档中说明interrupted()方法具有清除状态的功能。执行后具有将状态标识清除为false的功能。

this.isInterrupted()😗测试线程是否已经中断,但是不能清除状态标识。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void main(String[] args) {
Thread thread = new Thread() {
public void run() {
System.out.println("线程启动了");
while (!isInterrupted()) {
System.out.println(isInterrupted());//调用 interrupt 之后为true
}
System.out.println("线程结束了");
}
};
thread.start();

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
System.out.println("线程是否被中断:" + thread.isInterrupted());//true
}

来一个综合的例子:

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
public class test1 {

static volatile boolean flag = true;

public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("开始休眠");
try {
Thread.sleep(100 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("结束休眠,开始死循环");
while (flag) {
}
System.out.println("------------------子线程结束------------------");
}
});
thread.start();

Scanner scanner = new Scanner(System.in);
System.out.println("输入1抛出一个中断异常,输入2修改循环标志位,输入3判断线程是否阻塞,输入其他结束Scanner\n");
while (scanner.hasNext()) {
String text = scanner.next();
System.out.println("你输入了:" + text + "\n");
if ("1".equals(text)) {
thread.interrupt();
} else if ("2".equals(text)) {
flag = false; //如果不设为false,主线程结束后子线程仍在运行
} else if ("3".equals(text)) {
System.out.println(thread.isInterrupted());
} else {
scanner.close();
break;
}
}
System.out.println("------------------主线程结束------------------");
}
}

不能结束的情况

注意下面这种是根本不能结束的情况!

class Test {
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    public static void main(String[] args) {
Thread thread = new Thread() {
public void run() {
System.out.println("线程启动了");
while (true) {//对于这种情况,即使线程调用了intentrupt()方法并且isInterrupted(),但线程还是会继续运行,根本停不下来!
System.out.println(isInterrupted());//调用interrupt之后为true
}
}
};
thread.start();
thread.interrupt();//注意,此方法不会中断一个正在运行的线程,它的作用是:在线程受到阻塞时抛出一个中断信号,这样线程就得以退出阻塞的状态
while (true) {
System.out.println("是否isInterrupted:" + thread.isInterrupted());//true
}
}
}

关于interrupted()和isInterrupted()方法的注意事项说明

interrupted()是静态方法:*内部实现是调用的当前线程的isInterrupted(),并且会重置当前线程的中断状态。

测试当前线程是否已经中断(静态方法)。返回的是上一次的中断状态,并且会清除该状态,所以连续调用两次,第一次返回true,第二次返回false。

isInterrupted()是实例方法:是调用该方法的对象所表示的那个线程的isInterrupted(),不会重置当前线程的中断状态

测试线程当前是否已经中断,但是不能清除状态标识。

测试方法验证:

第一个红框中断的线程是我们自己创建的thread线程,我调用的interrupted(),由上面源码可知是判断当前线程的中断状态,当前线程是main线程,我根本没有中断过main线程,所以2次调用均返回“false”。

第一个红框中断的线程是当前线程(main线程),我调用的interrupted(),由上面源码可知是判断当前线程的中断状态,当前线程是main线程,所以第1次调用结果返回“true”,因为我确实中断了main线程。

由源码可知interrupted()调用的是isInterrupted(),并会重置中断状态,所以第一次调用之后把中断状态给重置了,从中断状态重置为非中断状态,所以第2次调用的结果返回“false” 。

个红框中断的线程是我们自己创建的thread线程,我调用的isInterrupted(),由上面源码可知是判断执行该方法的对象所表示线程的中断状态,也就是thread引用所表示的线程的中断状态,所以第1次调用结果返回“true”。

由源码可知isInterrupted()不会重置中断状态,所以第一次调用之后没有把中断状态给重置(从中断状态重置为非中断状态),所以第2次调用的结果还返回“true”。

生产者和消费者的关系

面试的:单例模式、排序算法、生产者和消费者、死锁。

Synchronized版本

com.guocl.pc;
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
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* 线程间的通信问题:生产者和消费者的问题! 等待唤醒 通知唤醒
* 线程交替执行 A B同时操作一个变量
* A num+1
* B num-1
*/
public class ConsumeAndProduct {
public static void main(String[] args) {
Data data = new Data();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();

new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();

new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();

new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"D").start();

}
}

//等待 业务 通知
class Data{
private int num = 0;

//生产者 +1
public synchronized void increment() throws InterruptedException {
//判断等待
if (num != 0){
this.wait();
}
num++;
System.out.println(Thread.currentThread().getName() + "=>" + num);
//通知其他线程 我执行完毕了
this.notifyAll();
}

//消费者 -1
public synchronized void decrement() throws InterruptedException {
//判断等待
if (num == 0){
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName() + "=>" + num);
// 通知其他线程 -1 执行完毕
this.notifyAll();
}

}
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
C=>0
B=>1
A=>2
D=>1
D=>0
A=>1
B=>2
C=>1
C=>0
B=>1
A=>2
D=>1
D=>0
A=>1
B=>2
C=>1
C=>0
B=>1
A=>2
D=>1
D=>0
A=>1
B=>2
C=>1
C=>0
B=>1
A=>2
D=>1
D=>0
A=>1
B=>2
C=>1
C=>0
B=>1
A=>2
D=>1
D=>0
B=>1
C=>0

Process finished with exit code 0

存在问题(虚假唤醒)

虚假唤醒

参考文章:https://blog.csdn.net/weixin_45668482/article/details/117373700

解决方式: if改在while即可,防止虚假唤醒

结论:wait方法执行时,当前对应的线程会释放获取的当前对象锁,并被加入wait Set中,在被唤醒后,当前线程会重新进入就绪状态准备抢占CPU时间片,在重新获取该对象后,该线程将在wait方法返回后恢复原来挂起前的状态,继续向下执行 , 我们等待的方法是在if判断内的,如下述代码:

-1
1
2
3
4
5
6
7
8
9
10
public synchronized void decrement() throws InterruptedException {
//判断等待
if (num == 0){
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName() + "=>" + num);
// 通知其他线程 -1 执行完毕
this.notifyAll();
}

我们如果使用if判断的话,直接继续运行if代码块之后的代码,不会去重新判断if条件;而使用while的话,也会从wait之后的代码开始运行,但是唤醒后会重新判断循环条件(while语句会重新循环判断并执行),如果不成立才会执行while代码块之后的代码,成立的话继续执行wait。

while,如下述代码:

1
2
3
4
5
6
7
8
9
10
11
12
//消费者 -1
public synchronized void decrement() throws InterruptedException {
//判断等待
while (num == 0){
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName() + "=>" + num);
// 通知其他线程 -1 执行完毕
this.notifyAll();
}

Lock版

Condition

1680097974324

实现生产者和消费者代码

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
69
70
71
72
73
74
75
package com.guocl.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockCAP {
public static void main(String[] args) {
Data2 data2 = new Data2();

new Thread(() -> {
for (int i = 0; i < 10; i++) {
data2.increment();
}
},"A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data2.decrement();
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data2.increment();
}
}, "C").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data2.decrement();
}
}, "D").start();

}

}

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

public void increment(){
lock.lock();
try {
while (num != 0) {
condition.await();
}
num++;
System.out.println(Thread.currentThread().getName() + "=>" + num);
// 通知其他线程 +1 执行完毕
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() + "=>" + num);
// 通知其他线程 +1 执行完毕
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}

Condition的优势

精确的通知和唤醒线程

如果我们要指定通知的下一个进行顺序怎么办呢? 我们可以使用Condition来指定通知进程~

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.guocl.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionDemo {

public static void main(String[] args) {
Data3 data3 = new Data3();

new Thread(() -> {
for (int i = 0; i < 10; i++) {
data3.printA();
}
},"A").start();

new Thread(() -> {
for (int i = 0; i < 10; i++) {
data3.printB();
}
},"B").start();

new Thread(() -> {
for (int i = 0; i < 10; i++) {
data3.printC();
}
},"C").start();

}
}

class Data3{
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
private int num = 1;// 1A 2B 3C

public void printA(){
System.out.println("进入了A方法");
lock.lock();
try {
while (num != 1){
System.out.println("------A方法等待");
condition1.await();
}
System.out.println(Thread.currentThread().getName() + "==> AAAA" );
num = 2;
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}

public void printB(){
System.out.println("进入了B方法");
lock.lock();
try {
while (num != 2) {
System.out.println("------B方法等待");
condition2.await();
}
System.out.println(Thread.currentThread().getName() + "==> BBBB" );
num = 3;
condition3.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}

public void printC(){
System.out.println("进入了C方法");
lock.lock();
try {
while(num != 3){
System.out.println("------C方法等待");
condition3.await();
}
System.out.println(Thread.currentThread().getName() + "==> CCCC" );
num = 1;
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}

8锁现象

如何平判断锁的是谁?

锁会锁住:对象、Class

深刻理解我们的锁

问题1:两个同步方法,先执行发短息还是打电话?

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
package com.guocl.lock8;

import java.util.concurrent.TimeUnit;

/**
* 问题1:两个同步方法,先执行发短信还是打电话
*/
public class LockPro1 {
public static void main(String[] args) throws InterruptedException {
Phone phone = new Phone();

new Thread(()->{phone.sendMs();}).start();

//睡一秒
TimeUnit.SECONDS.sleep(1);

new Thread(()->{phone.call();}).start();
}

}

class Phone{
public synchronized void sendMs(){
System.out.println("发短信");
}

public synchronized void call(){
System.out.println("打电话");
}
}

1
2
3
发短信
打电话

为什么? 如果你认为是顺序在前? 这个答案是错误的!

问题2:我们再来看:我们让发短信延迟4S

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
package com.guocl.lock8;

import java.util.concurrent.TimeUnit;

/**
* 问题1:两个同步方法,先执行发短信还是打电话
* 让短信延迟4S
*/
public class LockPro2 {
public static void main(String[] args) throws InterruptedException {
Phone2 phone2 = new Phone2();

new Thread(()->{
try {
phone2.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();

//睡一秒
TimeUnit.SECONDS.sleep(1);

new Thread(()->{phone2.call();}).start();
}

}

class Phone2{
public synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}

public synchronized void call(){
System.out.println("打电话");
}
}

1
2
3
发短信
打电话

1
2
并不是顺序执行,而是synchronized锁住的对象是方法的调用!对于两个方法用的是同一个锁,谁先拿到谁先执行,另外一个等待。 ----》锁的new出来的对象。

问题3:加一个普通方法

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
package com.guocl.lock8;

import java.util.concurrent.TimeUnit;
/**
* 问题1:两个同步方法,先执行发短信还是打电话
* 让短信延迟4S
* 加一个普通方法
*/
public class LockPro3 {
public static void main(String[] args) throws InterruptedException {
Phone3 phone3 = new Phone3();

new Thread(()->{
try {
phone3.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();

//睡一秒
TimeUnit.SECONDS.sleep(1);

new Thread(()->{phone3.hello();}).start();
}

}

class Phone3{
public synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}

public synchronized void call(){
System.out.println("打电话");
}

public void hello(){
System.out.println("hello");
}
}

1
2
3
hello
发短信

1
2
hello是一个普通方法,不受synchronized锁的影响,不用等待锁的释放。 ----》锁的new出来的对象。

问题4:我们使用的是两个对象,一个调用发短信,一个调用打电话,顺序如何?

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
package com.guocl.lock8;

import java.util.concurrent.TimeUnit;

public class LockPro4{
public static void main(String[] args) throws InterruptedException {
Phone4 phone41 = new Phone4();
Phone4 phone42 = new Phone4();

new Thread(()->{
try {
phone41.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();

//睡一秒
TimeUnit.SECONDS.sleep(1);

new Thread(()->{phone42.call();}).start();
}

}

class Phone4{
public synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}

public synchronized void call(){
System.out.println("打电话");
}

public void hello(){
System.out.println("hello");
}
}

1
2
3
打电话
发短信

1
2
两个对象两把锁,不会出现等待的情况,发短信睡了4秒,所以先执行打电话。 ----》锁的new出来的对象。

两个对象两把锁,不会出现等待的情况,发短信睡了4秒,所以先执行打电话。 ——》锁的new出来的对象。

  • 一个对象
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
package com.guocl.lock8;

import java.util.concurrent.TimeUnit;
/**
* 问题3:两个同步方法,先执行发短信还是打电话
* 让短信延迟4S
* 两个静态方法,一个对象
*/
public class LockPro5 {
public static void main(String[] args) throws InterruptedException {
Phone5 phone5 = new Phone5();

new Thread(()->{
try {
phone5.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();

//睡一秒
TimeUnit.SECONDS.sleep(1);

new Thread(()->{phone5.call();}).start();
}

}

class Phone5{
public static synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}

public static synchronized void call(){
System.out.println("打电话");
}

}

1
2
3
发短信
打电话

  • 两个对象
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
package com.guocl.lock8;

import java.util.concurrent.TimeUnit;
/**
* 问题3:两个同步方法,先执行发短信还是打电话
* 让短信延迟4S
* 两个静态方法,两个对象
*/
public class LockPro6 {
public static void main(String[] args) throws InterruptedException {
Phone6 phone61 = new Phone6();
Phone6 phone62 = new Phone6();

new Thread(()->{
try {
phone61.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();

//睡一秒
TimeUnit.SECONDS.sleep(1);

new Thread(()->{phone62.call();}).start();
}

}

class Phone6{
public static synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}

public static synchronized void call(){
System.out.println("打电话");
}

}

1
2
3
发短信
打电话

原因是什么呢?

为什么加了static就始终前面一个对象先执行呢!什么后面会等待呢?

原因:对象static静态方法来说,类在加载的时候就加载了静态方法,对整个类Class来说只有一份,对于不同的对象使用的是同一个Class模板,相当于这个方法是属于这个类的,如果静态static方法使用synchronized 锁定,那么这个synchronized 锁会锁住Class模板,不管多少对象,这个静态的锁都只有一把,谁先拿到谁先执行。

问题7:我们使用一个静态同步方法,一个对象调用的顺序是什么?

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
package com.guocl.lock8;

import java.util.concurrent.TimeUnit;
/**
* 问题3:两个同步方法,先执行发短信还是打电话
* 让短信延迟4S
* 一个静态方法,一个对象
*/
public class LockPro7 {
public static void main(String[] args) throws InterruptedException {
Phone7 phone7 = new Phone7();

new Thread(()->{
try {
phone7.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();

//睡一秒
TimeUnit.SECONDS.sleep(1);

new Thread(()->{phone7.call();}).start();
}

}

class Phone7{
public static synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}

public synchronized void call(){
System.out.println("打电话");
}

}

1
2
3
打电话
发短信

1
2
static锁的是Class模板,非静态方法锁的是new出来的对象,互不影响,不存在等待。

问题8:

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
package com.guocl.lock8;

import java.util.concurrent.TimeUnit;
/**
* 问题3:两个同步方法,先执行发短信还是打电话
* 让短信延迟4S
* 一个静态方法,两个对象
*/
public class LockPro8 {
public static void main(String[] args) throws InterruptedException {
Phone8 phone81 = new Phone8();
Phone8 phone82 = new Phone8();

new Thread(()->{
try {
phone81.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();

//睡一秒
TimeUnit.SECONDS.sleep(1);

new Thread(()->{phone82.call();}).start();
}

}

class Phone8{
public static synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}

public synchronized void call(){
System.out.println("打电话");
}

}

1
2
3
打电话
发短信

1
2
两个对象也是同理,static锁的是Class模板,非静态方法锁的是new出来的对象,互不影响,不存在等待。

总结

  • 非静态方法锁的是new出来的对象,互不影响;

  • 静态方法锁的是Class模板,唯一;

    集合不安全

    面试知识点:工作中遇到哪些异常,并发修改异常,OOM内存溢出异常

    List不安全

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    package com.guocl.Collections;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.UUID;

    // ConcurrentModificationException并发修改异常!
    public class CollectionsTest {
    public static void main(String[] args) {
    List<Object> list = new ArrayList<>();

    for (int i = 1; i <= 30 ; i++) {
    new Thread(()->{
    list.add(UUID.randomUUID().toString().substring(0, 5));
    System.out.println(list);
    },String.valueOf(i)).start();
    }
    }
    }

    会导致ConcurrentModificationException并发修改异常!

    ArrayList在并发情况下是不安全的!

    解决方案:

    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
    package com.guocl.Collections;

    import java.util.*;
    import java.util.concurrent.CopyOnWriteArrayList;

    public class CollectionsTest {
    public static void main(String[] args) {
    // List<Object> list = new ArrayList<>();

    /**
    * 1、Vector<String> list = new Vector<>();
    * 2、List<String> list = Collections.synchronizedList(new ArrayList<>());
    * 3、List<String> list = new CopyOnWriteArrayList<>();
    */
    List<String> list = new CopyOnWriteArrayList<>();

    for (int i = 1; i <= 30 ; i++) {
    new Thread(()->{
    list.add(UUID.randomUUID().toString().substring(0, 5));
    System.out.println(list);
    },String.valueOf(i)).start();
    }
    }
    }

    CopyOnWriteArrayList:**写入时复制! COW 计算机程序设计领域的一种优化策略

    多个线程调用的时候,list是唯一的,读取的时候list是固定的,写入的时候给list复制一份给调用者,调用者写入副本,副本再添加到唯一的list中。避免在写入的时候被覆盖,造成数据问题!

    核心思想:如果有多个调用者(Callers)同时要求相同的资源(如内存或者是磁盘上的数据存储),他们会共同获取相同的指针指向相同的资源,直到某个调用者视图修改资源内容时,系统才会真正复制一份专用副本(private copy)给该调用者,而其他调用者所见到的最初的资源仍然保持不变。这过程对其他的调用者都是透明的(transparently)。此做法主要的优点是如果调用者没有修改资源,就不会有副本(private copy)被创建,因此多个调用者只是读取操作时可以共享同一份资源。

    读的时候不需要加锁,如果读的时候有多个线程正向CopyOnWriteArrayList添加数据,读还是会读到旧数据,因为写的时候不会锁住旧的CopyOnWriteArrayList。

    CopyOnWriteArrayList比Vector厉害在哪里?

    Vector底层是使用synchronized 关键字来实现的:效率特别低下。

    CopyOnWriteArrayList 使用的是Lock锁,效率会更加高效!

    set不安全

    Set和List同理可得:多线程情况下,普通的Set集合是线程不安全的;

    解决方案有两种:

    • 使用Collections工具类的synchronized 包装的Set类;
    • 使用CopyOnWriteArraySet 写入复制的 JUC解决方案;
    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
    package com.guocl.Collections;

    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Set;
    import java.util.UUID;
    import java.util.concurrent.CopyOnWriteArraySet;

    public class SetTest {
    public static void main(String[] args) {
    /**
    * 1、Set<String> set = Collections.synchronizedSet(new HashSet<>());
    * 2、Set<String> set = new CopyOnWriteArraySet<>();
    */
    Set<String> set = new CopyOnWriteArraySet<>();

    for (int i = 1; i <= 30; i++) {
    new Thread(() -> {
    set.add(UUID.randomUUID().toString().substring(0, 5));
    System.out.println(set);
    }).start();
    }

    }
    }

    HashSet底层是什么?

    hashSet底层就是一个HashMap

    Map不安全

    1
    2
    3
    4
    5
    //map 是这样用的吗?  不是,工作中不使用这个
    //默认等价什么? new HashMap<>(16,0.75);
    Map<String, String> map = new HashMap<>();
    //加载因子、初始化容量

    默认 加载因子是0.75 默认的 初始容量是16

    同样的HashMap基础类也存在并发异常!

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
package com.guocl.Collections;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class MapTest {
public static void main(String[] args) {
//map 是这样用的吗? 不是,工作中不使用这个
//默认等价什么? new HashMap<>(16,0.75);
/**
* Map<String, String> map = new HashMap<>();
* 解决方案
* 1、Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
* 2、Map<String, String> map = new ConcurrentHashMap<>();
*/
Map<String, String> map = new ConcurrentHashMap<>();
//加载因子、初始化容量
for (int i = 1; i < 100; i++) {
new Thread(() -> {
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 5));
System.out.println(map);
}).start();
}

}
}

研究ConcurrentHashMap底层原理

Callable(简单)

1、callable的介绍

callable和runnable的区别

  • callable可以有返回值
  • callable可以抛出异常
  • callable方法不同,run()/call()

1
通过源码分析:Callable接口的泛型就是call方法的返回值

3、分析Callable的启动

我们通过Thread的源码分析Thread的参数只有Runnable,不能直接启动Callable

通过画图分析Callable怎么才能通过Thread启动呢?———》通过Runnable


Runnable接口中有一个FutureTask实现类

FutureTask介绍

FutureTask的构造方法中的参数中有Callable和Runnable

下面我们通过代码看一下

1
2
3
4
5
6
7
//我们通常使用Runnable的启动是
new Thread(new Runnable()).start();
//因为FutureTask是Runnable的实现类,所以上面的启动代码等价于下面的这行代码
new Thread(new FutureTask<V>()).start();
//Callable是FutureTask的参数,所以启动方式就为
new Thread(new FutureTask<V>(Callable));

代码实例

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
package com.guocl.collable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//我们通常使用Runnable的启动是
//new Thread(new Runnable()).start();
//因为FutureTask是Runnable的实现类,所以上面的启动代码等价于下面的这行代码
//new Thread(new FutureTask<V>()).start();
//Callable是FutureTask的参数,所以启动方式就为
//new Thread(new FutureTask<V>(Callable))

new Thread().start();//怎么启动Callable
// 步骤解析:
MyThread thread = new MyThread();
FutureTask futureTask = new FutureTask(thread);

//运行两个Thread,只会输出一次结果-------》 结果会被缓存,效率高
new Thread(futureTask, "A").start();
new Thread(futureTask, "B").start();
//返回值
//这个get方法很有可能会被阻塞,如果在call方法中是一个耗时的方法,就会等待很长时间。
//所以我们一般情况下回把这一行放到最后,或者使用异步通信
Integer o = (Integer) futureTask.get();
System.out.println(o);

}
}

class MyThread implements Callable<Integer>{

@Override
public Integer call(){
System.out.println("call()");
return 1024;
}
}

  • 结果会被缓存
  • 输出线程返回值可能会被阻塞

常用的辅助类(必会)

CountDownLatch

减法计数器

1、主要方法:

  • countDown 减1操作;
  • await 等待计数器归零;

await等待计数器归零,就唤醒,再继续向下运行。

2、代码实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.guocl.threadUtil;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {

public static void main(String[] args) throws InterruptedException {
// 设置总数是6
CountDownLatch countDownLatch = new CountDownLatch(6);

for (int i = 0; i <= 8 ; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "==> Go Out");
countDownLatch.countDown();// 线程数量 -1
}, String.valueOf(i)).start();
}

countDownLatch.await();// 等待计数器归零 然后向下执行
System.out.println("close door");
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
0==> Go Out
1==> Go Out
2==> Go Out
3==> Go Out
4==> Go Out
5==> Go Out
6==> Go Out
close door
8==> Go Out
7==> Go Out

Process finished with exit code 0

CyclickBarrier

简称:加法计数器

代码实例

com.guocl.threadUtil;
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

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclickBarrierDemo {

public static void main(String[] args) {
// 主线程
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("召唤神龙");
});

for (int i = 0; i <= 7; i++) {
// 子线程
int i1 = i;
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "收集了第" + i1 + "颗龙珠");
try {
cyclicBarrier.await();// 加法计数 等待
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
1
2
3
4
5
6
7
8
9
10
Thread-0收集了第0颗龙珠
Thread-3收集了第3颗龙珠
Thread-2收集了第2颗龙珠
Thread-1收集了第1颗龙珠
Thread-4收集了第4颗龙珠
Thread-5收集了第5颗龙珠
Thread-6收集了第6颗龙珠
召唤神龙
Thread-7收集了第7颗龙珠

Semaphore

原理:

semaphore.acquire() 获得资源,如果资源已经使用完了,就等待资源释放后再进行使用!
semaphore.release()释放 ,会释放当前的信号量,然后唤醒等待的线程!
作用:

多个资源互斥时使用!并发限流,控制最大的线程数!

代码实例

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
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {

public static void main(String[] args) {

// 线程数量。停车位,限流
Semaphore semaphore = new Semaphore(3);

for (int i = 0; i < 6; i++) {
new Thread(() -> {
try {
semaphore.acquire(); // 得到
System.out.println(Thread.currentThread().getName() + "抢到车位");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release(); // 释放
}
}).start();
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Thread-0抢到车位
Thread-1抢到车位
Thread-2抢到车位
Thread-1离开车位
Thread-2离开车位
Thread-0离开车位
Thread-3抢到车位
Thread-5抢到车位
Thread-4抢到车位
Thread-3离开车位
Thread-4离开车位
Thread-5离开车位

Process finished with exit code 0

读写锁

ReadWriteLock

实现类:ReetrantReadWritelock

读可以被多个线程同时读,写的时候只能有一个线程去写。

  • 未加锁的代码实例
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
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCache myCatch = new MyCache();
for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(() -> {
myCatch.put(temp+"" , temp+"");
},String.valueOf(i)).start();
}

for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(() -> {
myCatch.get(temp+"");
},String.valueOf(i)).start();
}

}

}

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

//存
public void put(String key, Object value){
System.out.println(Thread.currentThread().getName() + "写入" + value);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "写入成功!");
}

//取
public void get(String key){
System.out.println(Thread.currentThread().getName()+"读取"+key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+"读取成功");
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2写入2
1写入1
1写入成功!
2写入成功!
3写入3
5写入5
5写入成功!
3写入成功!
4写入4
4写入成功!
1读取1
2读取2
1读取成功
2读取成功
3读取3
3读取成功
4读取4
4读取成功
5读取5
5读取成功

结论:不加锁的情况下,多线程的读写会造成数据不可靠的问题。

我们也可以采用synchronized这种重量锁和轻量锁 lock去保证数据的可靠。

但是这次我们采用更细粒度的锁:ReadWriteLock 读写锁来保证

  • 加锁代码实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1写入1
1写入成功!
2写入2
2写入成功!
4写入4
4写入成功!
3写入3
3写入成功!
5写入5
5写入成功!
1读取1
1读取成功
2读取2
2读取成功
3读取3
5读取5
3读取成功
5读取成功
4读取4
4读取成功

阻塞队列


BlockQueue
阻塞队列

是Collection的一个子类

什么情况下我们会用到阻塞队列

多线程并发处理、线程池

BlockingQueue有四组API

方式 抛出异常 不会抛出异常,有返回值 阻塞,等待 超时等待
添加 add() offer() put() offer(timenum.timeUnit)
移出 remove() poll() take() poll(timenum,timeUnit)
检测队首元素 element() peek()
抛出异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 抛出异常
*/
public static void test1(){
//需要初始化队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));

//抛出异常:java.lang.IllegalStateException: Queue full
// System.out.println(blockingQueue.add("d"));

System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//如果多移除一个
//这也会造成 java.util.NoSuchElementException 抛出异常
System.out.println(blockingQueue.remove());
}

  • 不抛出异常,有返回值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 不抛出异常,有返回值
*/
public static void test2(){
ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);

System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
//添加 一个不能添加的元素 使用offer只会返回false 不会抛出异常
System.out.println(blockingQueue.offer("d"));

System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
//弹出 如果没有元素 只会返回null 不会抛出异常
System.out.println(blockingQueue.poll());
}

  • 阻塞,等待
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 等待 一直阻塞
*/
public static void test3() throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

//
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
//如果队列已经满了, 再进去一个元素 这种情况会一直等待这个队列 什么时候有了位置再进去,程序不会停止
// blockingQueue.put("d");

System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
//如果我们再来一个 这种情况也会等待,程序会一直运行 阻塞
System.out.println(blockingQueue.take());
}

  • 超时等待
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 等待 超时阻塞
* 这种情况也会等待队列有位置 或者有产品 但是会超时结束
*/
public static void test4() throws InterruptedException {
ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);

blockingQueue.offer("a");
blockingQueue.offer("b");
blockingQueue.offer("c");

//超时时间2s 等待如果超过2s就结束等待
blockingQueue.offer("d", 2, TimeUnit.SECONDS);

blockingQueue.poll();
blockingQueue.poll();
blockingQueue.poll();
//超过两秒 我们就不要等待了
blockingQueue.poll(2, TimeUnit.SECONDS);

}

SynchronousQueue
同步队列

特点:

同步队列没有容量,也可以视为容量为1的队列;
进去一个元素,必须等待取出来之后,才能再往里面放入一个元素;
put方法 和 take方法

SynchronousQueue和 其他的BlockingQueue 不一样 它不存储元素;

put了一个元素,就必须从里面先take出来,否则不能再put进去值!

并且SynchronousQueue 的take是使用了lock锁保证线程安全的

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
package com.marchsoft.queue;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;


public class SynchronousQueue {
public static void main(String[] args) {
BlockingQueue<String> synchronousQueue = new java.util.concurrent.SynchronousQueue<>();
// 网queue中添加元素
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + "put 01");
synchronousQueue.put("1");
System.out.println(Thread.currentThread().getName() + "put 02");
synchronousQueue.put("2");
System.out.println(Thread.currentThread().getName() + "put 03");
synchronousQueue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
// 取出元素
new Thread(()-> {
try {
System.out.println(Thread.currentThread().getName() + "take" + synchronousQueue.take());
System.out.println(Thread.currentThread().getName() + "take" + synchronousQueue.take());
System.out.println(Thread.currentThread().getName() + "take" + synchronousQueue.take());
}catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}

线程池(重点)

线程池:三大创建方式、七大参数、四种拒绝策略

池化技术

程序的运行,本质:占用系统的资源! 我们需要去优化资源的使用 ====> 池化技术

例如:线程池、JDBC的连接池、内存池、对象池等等…

资源的创建、销毁十分消耗资源

池化技术:事先准备好一些资源,如果有人要用,就来我这里拿,用完之后还给我,以此来提高效率。

线程池的好处:

1、降低资源的消耗;

2、提高响应的速度;

3、方便管理;

线程复用、可以控制最大并发、管理线程;

线程池:三大方法、七大参数、四种策略

三大方法

ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程
ExecutorService threadPool2 = Executors.newFixedThreadPool(5); //创建一个固定的线程池的大小
ExecutorService threadPool3 = Executors.newCachedThreadPool(); //可伸缩的

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
package com.guocl.ThreadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolDemo {

public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();// 单个线程
ExecutorService threadPool = Executors.newFixedThreadPool(5);// 创建一个固定的线程池的大小
ExecutorService threadPool = Executors.newCachedThreadPool();// 单个线程

try {
for (int i = 1; i <= 10; i++) {
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + ":OK");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}

}

}

七大参数

创建线程时,不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式。

阿里巴巴的Java操作手册中明确说明:对于Integer.MAX_VALUE初始值较大,所以一般情况我们要使用底层的 ThreadPoolExecutor来创建线程池。

使用 ThreadPoolExecutor创建线程池!

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
package com.guocl.ThreadPool;

import java.util.concurrent.*;

public class ThreadPoolDemo {

public static void main(String[] args) {
// ExecutorService threadPool = Executors.newSingleThreadExecutor();// 单个线程
// ExecutorService threadPool = Executors.newFixedThreadPool(5);// 创建一个固定的线程池的大小
// ExecutorService threadPool = Executors.newCachedThreadPool();// 单个线程
//获取cpu 的核数
int max = Runtime.getRuntime().availableProcessors();
//创建线程池
ExecutorService threadPool = new ThreadPoolExecutor(
2,
max,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);


try {
for (int i = 1; i <= 5; i++) {
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + ":OK");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}

}

}

我们看了一下三种创建线程池方法的底层都是调用了ThreadPoolExecutor来创建的,ThreadPoolExecutor有七大参数,我们来看一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public ThreadPoolExecutor(int corePoolSize,  //核心线程池大小
int maximumPoolSize, //最大线程池的大小
long keepAliveTime, //超时时间,超过了就会释放线程
TimeUnit unit, //超时单位
BlockingQueue<Runnable> workQueue, //阻塞队列, 用来存储排队等待的线程
ThreadFactory threadFactory, //线程工厂 创建线程的,我们一般不动
RejectedExecutionHandler handler //拒绝策略,有四种
) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}

四种拒绝策略

1.new ThreadPoolExecutor.AbortPolicy(): //该拒绝策略为:银行满了,还有人进来,不处理这个人的,并抛出异常

超出最大承载,就会抛出异常:队列容量大小+maxPoolSize。

new ThreadPoolExecutor.CallerRunsPolicy(): //该拒绝策略为:哪来的去哪里 main线程进行处理。

new ThreadPoolExecutor.DiscardPolicy(): //该拒绝策略为:队列满了,丢掉异常,不会抛出异常。

new ThreadPoolExecutor.DiscardOldestPolicy(): //该拒绝策略为:队列满了,尝试去和最早的进程竞争,不会抛出异常。

如果设置线程池的大小

1、CPU密集型:电脑的核数是几核就选择几;选择maximunPoolSiz 的大小

1
2
3
4
5
6
7
8
9
10
11
12
// 获取cpu 的核数
int max = Runtime.getRuntime().availableProcessors();
ExecutorService service =new ThreadPoolExecutor(
2,
max,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);

2、I/O密集型:

在程序中有15个大型任务,IO十分占用资源;I/O密集型就是判断我们程序中十分耗I/O的线程数量,大约就是最大I/O的一倍到两倍之间。

四大函数式接口

新时代的程序员: lambda表达式、链式编程、函数式接口、Stream流式计算

函数式接口:只有一个方法的接口

Function函数型接口

Function函数型接口,有一个输入参数,有一个输出参数,只要是 函数型接口 可以用 lambda表达式简化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.guocl.function;

import java.util.function.Function;

public class FunctionDemo {

public static void main(String[] args) {
// Function function = new Function<String, String>() {
// @Override
// public String apply(String str) {
// System.out.println(str);
// return str;
// }
// };
Function<String, String> function = (str) -> {return str;};
System.out.println(function.apply("aaa"));
}
}

Predicate 断定型接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

import com.sun.xml.internal.ws.util.StringUtils;

import java.util.function.Predicate;

public class PredicateDemo {

public static void main(String[] args) {
// Predicate predicate = new Predicate<String>() {
// @Override
// public boolean test(String o) {
// if (o != null){
// return true;
// }
// return false;
// }
// };

Predicate<String> predicate = (str) -> { return true;};

System.out.println(predicate.test("A"));
}
}

Consumer 消费型接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.function.Consumer;
import java.util.function.Predicate;

public class PredicateDemo {

public static void main(String[] args) {
// Consumer consumer = new Consumer<String>() {
// @Override
// public void accept(String o) {
// System.out.println("1111");
// }
// };

Consumer<String> consumer = (str) -> { System.out.println("1111");};

consumer.accept("A");
}
}

Suppier 供给型接口

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
package com.guocl.function;


import com.sun.xml.internal.ws.util.StringUtils;

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class PredicateDemo {

public static void main(String[] args) {

// Supplier supplier = new Supplier<String>() {
// @Override
// public String get() {
// return "1";
// }
// };

Supplier<String> supplier = () -> { return "1";};

System.out.println(supplier.get());
}
}

Stream流式计算

什么是Stream流式计算

大数据:存储 + 计算

集合、Mysql本质都是存储东西的;

计算都应该交给流来操作!

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
package com.guocl.stream;

import com.guocl.stream.pojo.User;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;

/**
* Description:
* 题目要求: 用一行代码实现
* 1. Id 必须是偶数
* 2.年龄必须大于23
* 3. 用户名转为大写
* 4. 用户名倒序
* 5. 只能输出一个用户
**/
public class StreamDemo {

public static void main(String[] args) {
User u1 = new User(1, "a", 23);
User u2 = new User(2, "b", 23);
User u3 = new User(3, "c", 23);
User u4 = new User(6, "d", 24);
User u5 = new User(4, "e", 25);

List<User> list = Arrays.asList(u1, u2, u3, u4, u5);

list.stream()
.filter(u -> {return u.getId() % 2 == 0;})
.filter(u -> {return u.getAge() > 23;})
.map(u -> {return u.getName().toUpperCase();})
.sorted((uu1, uu2) -> {return uu2.compareTo(uu1);})
.limit(1)
.forEach(System.out::println);
}
}

ForkJoin

ForkJoin 在JDK1.7中出现,并行执行任务!提高效率。在大数据量速率会更快!

大数据中: MapReduce 核心思想–>把大任务拆分为小任务!

ForkJoin特点:工作窃取

实现原理: 双端队列 从上面和下面都可以去拿到任务进行执行!

如何使用ForkJoin?

1、通过ForkJoinPool来执行

2、计算任务 execute(ForkJoinTask<?> task)

3、计算类要去继承 ForkJoinTask

ForkJoin的计算案例

ForkJoin的计算类

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
package com.guocl.ff;

import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo extends RecursiveTask<Long> {
private long start;
private long end;
//临界值
private long temp = 1000000L;

public ForkJoinDemo(long start, long end){
this.start = start;
this.end = end;
}

/**
* 计算方法
* @return
*/
@Override
protected Long compute() {
if ((end - start) < temp){
Long sum = 0L;
for (Long i = start; i < end; i++) {
sum += i;
}
return sum;
}else {
// 使用ForkJoin 分而治之 计算
// 1、计算平均值
long middle = (start + end) / 2;
// 拆分任务,把线程压入线程队列
ForkJoinDemo forkJoinDemo1 = new ForkJoinDemo(start, middle);
forkJoinDemo1.fork();
ForkJoinDemo forkJoinDemo2 = new ForkJoinDemo(middle, end);
forkJoinDemo2.fork();

long taskSum = forkJoinDemo1.join() + forkJoinDemo2.join();
return taskSum;
}
}
}

测试类

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
package com.guocl.ff;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class ForkJoinTest {
private static final long SUM = 20_0000_0000;

public static void main(String[] args) throws ExecutionException, InterruptedException {
//test1();
test2();
test3();
}

public static void test1(){
long start = System.currentTimeMillis();
long sum = 0L;
for (int i = 0; i < SUM; i++) {
sum += i;
}
long end = System.currentTimeMillis();
System.out.println(sum);
System.out.println("时间:" + (end - start));
System.out.println("----------------------");
}

public static void test2() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long> task = new ForkJoinDemo(0L, SUM);
ForkJoinTask<Long> submit = forkJoinPool.submit(task);
Long along = submit.get();

System.out.println(along);
long end = System.currentTimeMillis();
System.out.println("时间:" + (end - start));
System.out.println("-----------");
}

public static void test3(){
long start = System.currentTimeMillis();

long sum = LongStream.range(0L, SUM).parallel().reduce(0, Long::sum);
System.out.println(sum);
long end = System.currentTimeMillis();
System.out.println("时间:" + (end - start));
System.out.println("-----------");
}

}

1
2
3
4
5
6
7
8
9
1999999999000000000
时间:20727
-----------
1999999999000000000
时间:659
-----------

Process finished with exit code 0

.parallel().reduce(0, Long::sum)使用一个并行流去计算整个计算,提高效率。

异步回调

Future 设计的初衷:对将来的某个事件结果进行建模!

其实就是前端 —》发送ajax异步请求给后端

但是我们平时都使用CompletableFuture

没有返回值的runAsync异步回调

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
package com.guocl.ff;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class FutureDemo {

public static void main(String[] args) throws ExecutionException, InterruptedException {
// 发起 一个 请求

System.out.println(System.currentTimeMillis());
System.out.println("---------------------");
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//发起一个异步任务
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+".....");
});
System.out.println(System.currentTimeMillis());
System.out.println("------------------------------");
//输出执行结果
System.out.println(future.get()); //获取执行结果
}
}

1
2
3
4
5
6
7
1666602291181
---------------------
1666602291275
------------------------------
ForkJoinPool.commonPool-worker-1.....
null

有返回值的supplyAsync异步回调

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
package com.guocl.ff;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class FutureDemo {

public static void main(String[] args) throws ExecutionException, InterruptedException {
// // 发起 一个 请求
// 成功的
// System.out.println(System.currentTimeMillis());
// System.out.println("---------------------");
// CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
// //发起一个异步任务
// try {
// TimeUnit.SECONDS.sleep(2);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName()+".....");
// });
// System.out.println(System.currentTimeMillis());
// System.out.println("------------------------------");
// //输出执行结果
// System.out.println(future.get()); //获取执行结果


//失败的
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync( () -> {
System.out.println(Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(2);
int i=1/0;
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1024;
});
System.out.println(completableFuture.whenComplete((t, u) -> {
// success 回调
System.out.println("t=>" + t); //正常的返回结果
System.out.println("u=>" + u); //抛出异常的 错误信息
}).exceptionally((e) -> {
// error回调
System.out.println(e.getMessage());
return 404;
}).get());
}
}


1
2
3
4
5
6
7
8
失败时候的返回值:

ForkJoinPool.commonPool-worker-1
t=>null
u=>java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
404

1
2
3
4
5
6
成功时候的返回值:

ForkJoinPool.commonPool-worker-1
t=>1024
u=>null
1024

whenComplete: 有两个参数,一个是t 一个是u

T:是代表的 正常返回的结果;

U:是代表的 抛出异常的错误信息;

如果发生了异常,get可以获取到exceptionally返回的值;

16、JMM
16.1、对Volatile的理解
Volatile 是Java虚拟机提供 轻量级的同步机制

提到Volatile我们就会想到它的三个特点!

1、保证可见性

2、不保证原子性

3、禁止指令重排

如何实现可见性

volatile变量修饰的共享变量在进行写操作的时候会多出一行汇编:

0x01a3de1d:movb $0×0,0×1104800(%esi);0x01a3de24:lock addl $0×0,(%esp);

Lock前缀的指令在多核处理器下回引发两件事:

将当前处理器缓存行的数据写回到系统内存。
这个写回内存的操作会使其他CPU里缓存了该内存地址的数据无效。
多处理器总线嗅探:

为了提高处理速度,处理器不直接和内存进行通信,而是先将系统内存的数据读到内部缓存后再进行操作,但操作不知道何时会写回到内存。如果对声明了volatile的变量进行写操作,JVM就会向处理器发送一条lock前缀的指令,将这个变量所在缓存行的数据写回到系统内存。但是在 多处理器下 ,为了保证各个处理器的缓存是一致的,就会实现缓存一致性协议, 每个处理器通过嗅探在总线上传播的数据来检查自己的缓存是不是过期了,如果处理器发现自己缓存行对应的内存地址被修改,就会将当前处理器的缓存行设置无效状态 ,当处理器对这个数据进行修改操作的时候,会重新从系统内存中把数据读取到处理器缓存中。

16.2、什么是JMM
JMM:JAVA内存模型,不存在的东西,是一个概念也是一个约定!

关于JMM的一些同步的约定

1、线程解锁前,必须把共享变量立刻刷回主存;

2、线程加锁前,必须 读取主存中的最新值到工作内存中;

3、加锁和解锁是同一把锁;

线程中分为 工作内存、主内存。

8种操作

Read(读取):作用于主内存变量,它把一个变量的值从主内存传输到线程的工作内存中,以便随后的load动作使用;

load(载入):作用于工作内存的变量,它把read操作从主存中变量放入工作内存中;

Use(使用):作用于工作内存中的变量,它把工作内存中的变量传输给执行引擎,每当虚拟机遇到一个需要使用到变量的值,就会使用到这个指令;

assign(赋值):作用于工作内存中的变量,它把一个从执行引擎中接受到的值放入工作内存的变量副本中;

store(存储):作用于主内存中的变量,它把一个从工作内存中一个变量的值传送到主内存中,以便后续的write使用;

write(写入):作用于主内存中的变量,它把store操作从工作内存中得到的变量的值放入主内存的变量中;

lock(锁定):作用于主内存的变量,把一个变量标识为线程独占状态;

unlock(解锁):作用于主内存的变量,它把一个处于锁定状态的变量释放出来,释放后的变量才可以被其他线程锁定;

JMM对这8种操作给了相应的规定:

不允许read和load、store和write操作之一单独出现。即使用了read必须load,使用了store必须write;
不允许线程丢弃他最近的assign操作,即工作变量的数据改变了之后,必须告知主存;
不允许一个线程将没有assign的数据从工作内存同步回主内存;
一个新的变量必须在主内存中诞生,不允许工作内存直接使用一个未被初始化的变量。就是对变量实施use、store操作之前,必须经过assign和load操作;
一个变量同一时间只有一个线程能对其进行lock。多次lock后,必须执行相同次数的unlock才能解锁;
如果对一个变量进行lock操作,会清空所有工作内存中此变量的值,在执行引擎使用这个变量前,必须重新load或assign操作初始化变量的值;
如果一个变量没有被lock,就不能对其进行unlock操作。也不能unlock一个被其他线程锁住的变量;
对一个变量进行unlock操作之前,必须把此变量同步回主内存
遇到问题

这时会出现一个问题,如线程A和线程B同时使用了主存的一个数据,线程B修改了值,但是线程A不能及时可见。

遇到问题:程序不知道主存中的值已经被修改过了! 下面解答

volatile

保证可见性

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
package com.guocl.volatileDemo;

import java.util.concurrent.TimeUnit;

public class volatiletest {

//如果不加volatile,程序会一直跑,因为开启的线程不知道主存的num变成了1
private volatile static Integer num = 0;

public static void main(String[] args) {

//子线程
new Thread(() -> {
while (num == 0){
}
}).start();

try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}

num = 1;
System.out.println(num);
}
}

不保证原子性

原子性:不可分割;

线程A在执行任务的时候,不能被打扰,也不能被分割,要么同时成功,要么同时失败。

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
package com.guocl.volatileDemo;

public class VolatileTest2 {
private volatile static Integer num = 0;

public static void add(){
//++ 不是一个原子性操作
num++;
}

public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
new Thread(() -> {
for (int j = 1; j < 100; j++) {
add();
}
}).start();
}

while (Thread.activeCount() > 2){
//当线程数小于2的时候就停止,因为有两个默认线程:mian、GC
Thread.yield();
}
System.out.println(Thread.currentThread().getName() + ", num=" + num);
}
}

1
2
3
4
main, num=1980

Process finished with exit code 0

如果不加lock和synchronized ,怎么样保证原子性?

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
package com.guocl.volatileDemo;

import java.util.concurrent.atomic.AtomicInteger;

public class VolatileTest2 {
private static volatile AtomicInteger num = new AtomicInteger();

public static void add(){
//底层是CAS保证原子性,效率很高
num.incrementAndGet();
}

public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
new Thread(() -> {
for (int j = 1; j <= 1000; j++) {
add();
}
}).start();
}

while (Thread.activeCount() > 2){
//当线程数小于2的时候就停止,因为有两个默认线程:mian、GC
Thread.yield();
}
System.out.println(Thread.currentThread().getName() + ", num=" + num);
}
}

这些原子类的底层都是直接和操作系统挂钩,是在内存中修改值的。

Unsafe类是一个很特殊的存在;

禁止指令重排

什么是指令重排

我们写程序时,计算机并不是按照我们自己写的那样去执行的。

源代码–>编译器优化–>指令并行也可能会重排–>内存系统也会重排–>执行

处理器在进行指令重排的时候,会考虑数据之间的依赖性!

1
2
3
4
5
6
7
8
9
int x=1; //1
int y=2; //2
x=x+5; //3
y=x*x; //4

//我们期望的执行顺序是 1_2_3_4 可能执行的顺序会变成2134 1324
//可不可能是 4123? 不可能的
1234567

可能造成的影响结果:前提:a b x y这四个值 默认都是0

线程A 线程B
x=a y=b
b=1 a=2
正常的结果: x = 0; y =0;

线程A 线程B
b=1 a=2
x=a y=b
可能在线程A中会出现,先执行b=1,然后再执行x=a;

在B线程中可能会出现,先执行a=2,然后执行y=b;

那么就有可能结果如下:x=2; y=1.

Volatile可以避免指令重排

Volatile中会加一道内存的屏障,这个内存屏障可以保证在这个屏障中的指令顺序。

内存屏障:CPU指令。

作用:

1、保证特定的操作的执行顺序;

2、可以保证某些变量的内存可见性(利用这些特性,就可以保证volatile实现的可见性)

总结:

  • volatile可以保证可见性;
  • 不能保证原子性
  • 由于内存屏障,可以保证避免指令重排的现象发生

面试官:那么你知道在哪里用这个内存屏障用得最多呢?单例模式

玩转单例模式

饿汉式 、懒汉式(DCL懒汉式)

18.1、饿汉式

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
package com.guocl.Singleton;

/**
* 饿汉式单例
*/
public class Hungry {

/**
* 可能会浪费空间
*/
private byte[] data1 = new byte[1024*1024];
private byte[] data2 = new byte[1024*1024];
private byte[] data3 = new byte[1024*1024];
private byte[] data4 = new byte[1024*1024];

private Hungry(){

}

private final static Hungry hungry = new Hungry();

public static Hungry getInstance(){
return hungry;
}
}


DCL懒汉式

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
69
70
71
72
73
74
75
76
77
78
79
package com.guocl.Singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class LazyMan {

private static boolean key = false;

private LazyMan(){
//当用反射创建对象时,会破坏单例模式,这时我们需要在构造方法处 加锁
synchronized (LazyMan.class){
//当一个对象调用单例创建,其他对象用反射创建时,这时我们需要在构造方法处判断对象是否为空
//但是当两个对象都用反射创建时,此校验就没用了
// if (lazyMan != null){
// throw new RuntimeException("不要试图使用反射破坏异常");
// }
//当两个对象都用反射创建时,我们使用红绿灯的方式来校验(标志位)
if (key==false){
key = true;
}else {
throw new RuntimeException("不要试图使用反射破坏异常");
}
}
System.out.println(Thread.currentThread().getName() + "OK");
}

private volatile static LazyMan lazyMan;

//双重检测模式的懒汉式单例, DCL单例
public static LazyMan getInstance(){
if (lazyMan == null){
//当多线程调用时,会创建多个不同的对象,这时我们需要加锁
synchronized (LazyMan.class){
/**
* new LazyMan();有三步
* 1、分配内存空间
* 2、执行构造方法,初始化对象
* 3、把这个对象指向这个空间
*
* 这时有可能出现指令重排问题
* 比如执行的顺序是1 3 2 等
* 我们就可以添加volatile保证指令重排问题
*/
lazyMan = new LazyMan();//不是一个原子性操作
}
}
return lazyMan;
}

public static void main(String[] args) throws Exception {
//多线程调用懒汉式单例模式,需要加锁
// for (int i = 0; i < 10; i++) {
// new Thread(() -> {
// System.out.println(LazyMan.getInstance());
// }).start();
// }

// LazyMan lazyMan1 = LazyMan.getInstance();
// System.out.println("lazyMan1" + lazyMan1);

//使用红绿灯的方式来校验单例,也是可以破解的。
//我们可以反编译这个类,看到红绿灯的变量名,无视标志位的私有化
Field key = LazyMan.class.getDeclaredField("key");
key.setAccessible(true);
// 使用反射来破解单例模式
// 反射私有的无参构造
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
//无视私有的构造器
declaredConstructor.setAccessible(true);
LazyMan lazyMan1 = declaredConstructor.newInstance();
System.out.println("lazyMan1" + lazyMan1);
//把key变量变成false
key.set(lazyMan1, false);
LazyMan lazyMan2 = declaredConstructor.newInstance();
System.out.println("lazyMan2" + lazyMan2);
}
}

结论:懒汉式无论怎么检测都是不安全的,使用枚举才是安全的

静态内部类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.guocl.Singleton;

/**
* 静态内部类
*/
public class Holder {

private Holder(){

}

public static Holder getInstance(){
return InnerClass.holder;
}

private static class InnerClass{
private static final Holder holder = new Holder();
}
}

枚举

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
package com.guocl.Singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//enum 是什么? enum本身是一个Class类
public enum EnumSingle {
INSTANCE;
public EnumSingle getInstance(){
return INSTANCE;
}
}

class Test{
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
EnumSingle instance1 = EnumSingle.INSTANCE;
//开始我们看源码 枚举是一个无参构造,但是报的错不是我们 期望的。
//我们通过使用工具反编译,发现枚举默认的是一个两个参数的有参构造
// Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(null);
Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class, int.class);
declaredConstructor.setAccessible(true);

EnumSingle instance2 = declaredConstructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
}
}

使用枚举,我们就可以防止反射破坏了.

枚举类型的最终反编译源码:

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
public final class EnumSingle extends Enum
{

public static EnumSingle[] values()
{
return (EnumSingle[])$VALUES.clone();
}

public static EnumSingle valueOf(String name)
{
return (EnumSingle)Enum.valueOf(com/ogj/single/EnumSingle, name);
}

private EnumSingle(String s, int i)
{
super(s, i);
}

public EnumSingle getInstance()
{
return INSTANCE;
}

public static final EnumSingle INSTANCE;
private static final EnumSingle $VALUES[];

static
{
INSTANCE = new EnumSingle("INSTANCE", 0);
$VALUES = (new EnumSingle[] {
INSTANCE
});
}
}

深入理解CAS

什么是CAS

大厂必须深入研究底层!!!!修内功!操作系统、计算机网络、组成原理、数据结构

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
package com.guocl.cas;

import java.util.concurrent.atomic.AtomicInteger;

public class CasDemo {

public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(2020);

// boolean compareAndSet(int expect, int update)
// 期望值、更新值
// 如果实际值 和 期望值相同,那么就会更新
// 如果实际值 和 期望值不相同,那么就不会更新
System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get());


// ++操作 现在实际值为2021
atomicInteger.getAndIncrement();
// 因为期望值是2020 实际上是2021,所以修改失败
System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get());
}
}

之前讲volatile的时候,谈到了Unsafe类。

Unsafe类

java可以通过Unsafe 类来操作 内存

方法解释:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//该方法功能是Interger类型加1
public final int getAndIncrement() {
//主要看这个getAndAddInt方法
return unsafe.getAndAddInt(this, valueOffset, 1);
}

//var1 是this指针
//var2 是地址偏移量
//var4 是自增的数值,是自增1还是自增N
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
//获取内存值,这是内存值已经是旧的,假设我们称作期望值E
var5 = this.getIntVolatile(var1, var2);
//compareAndSwapInt方法是重点,
//var5是期望值,var5 + var4是要更新的值
//这个操作就是调用CAS的JNI,每个线程将自己内存里的内存值M
//与var5期望值E作比较(其实就是var1和var5作比较),如果相同将内存值M更新为var5 + var4,否则做自旋操作
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));

return var5;
}

总结

CAS:比较当前工作内存中的值 和 主内存中的值,如果这个值时期望的,则执行操作!如果不是就一直循环,使用的就是自旋锁。

缺点:

  • 循环会耗时;
  • 一次性只能保证一个共享变量的原子性;
  • 它会存在ABA问题

CAS:ABA问题?(狸猫换太子)

线程1:期望值是1,要变成2;

线程2:两个操作:

  • 1、期望值是1,变成3
  • 2、期望是3,变成1

所以对于线程1来说,A的值还是1,所以就出现了问题,骗过了线程1;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.guocl.cas;

import java.util.concurrent.atomic.AtomicInteger;

public class AbaDemo {

public static void main(String[] args) {

AtomicInteger atomicInteger = new AtomicInteger(2020);

//捣乱线程
System.out.println("a1:" + atomicInteger.compareAndSet(2020, 2021));
System.out.println("a2:" + atomicInteger.compareAndSet(2021, 2020));
System.out.println(atomicInteger.get());

System.out.println("b1" + atomicInteger.compareAndSet(2020, 2022));
System.out.println(atomicInteger.get());
}
}

1
2
3
4
5
6
7
8
a1:true
a2:true
2020
b1true
2022

Process finished with exit code 0

解决CAS的ABA问题需要 原子引用,也就是乐观锁的思想

原子引用

解决ABA问题,对应的思想:就是使用乐观锁!!!

带版本号的原子操作!

当我们使用原子操作泛型为Integer时,注意一个大坑:

Integer 使用了对象缓存机制,默认范围是-128~127,推荐使用静态工厂方法valueOf获取对象实例,而不是new,因为valueOf使用缓存,而new一定会创建新的对象分配新的内存空间。

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
package com.guocl.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

public class AtoRef {

/**AtomicStampedReference 注意,如果泛型是一个包装类,注意对象的引用问题
* 正常在业务操作,这里面比较的都是一个个对象
*/
static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(1, 1);

// CAS compareAndSet : 比较并交换!
public static void main(String[] args) {
new Thread(() -> {
// 获得新版本号
int stamp = atomicStampedReference.getStamp();
System.out.println("a1=>" + stamp);

try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 修改操作时,版本号更新 + 1
System.out.println(atomicStampedReference.compareAndSet(1, 2, stamp, atomicStampedReference.getStamp() + 1));
System.out.println("a2=>" + atomicStampedReference.getStamp());

// 重新把值改回去, 版本号更新 + 1
System.out.println(atomicStampedReference.compareAndSet(2, 1, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
System.out.println("a3=>" + atomicStampedReference.getStamp());

}, "a").start();

new Thread(() -> {
//获得版本号
int stamp = atomicStampedReference.getStamp();
System.out.println("b1=>" + stamp);

try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(atomicStampedReference.compareAndSet(1, 6, stamp, atomicStampedReference.getStamp() + 1));
System.out.println("b2=>" + atomicStampedReference.getStamp());
}, "b").start();
}

}

1
2
3
4
5
6
7
8
9
10
11
a1=>1
b1=>1
true
a2=>2
true
a3=>3
false
b2=>3

Process finished with exit code 0

各种锁的理解

公平锁、非公平锁

公平锁: 非常公平,不能够插队,必须先来后到!

非公平锁:非常不公平,可以插队!

Synchronized和Lock锁默认的都是非公平锁,看下面代码实例!

1
2
3
4
5
6
7
8
9
10
// 默认非公平锁
public ReentrantLock() {
sync = new NonfairSync();
}

// 公平锁
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}

可重入锁`

又叫递归锁

手写可重入锁

Synchronized

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
package com.guocl.Lock;

public class Demo1 {

public static void main(String[] args) {
Phone phone = new Phone();

new Thread(() ->{
phone.sms();
}, "A").start();

new Thread(() -> {
phone.call();
}, "B").start();
}

}

class Phone{
public synchronized void sms(){
System.out.println(Thread.currentThread().getName() + "sms");
call();// 这里也有锁
}

public synchronized void call(){
System.out.println(Thread.currentThread().getName() + "call");
}
}

Lock

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
package com.guocl.Lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo2 {

public static void main(String[] args) {
Phone2 phone2 = new Phone2();

new Thread(() ->{
phone2.sms();
}, "A").start();

new Thread(() -> {
phone2.call();
}, "B").start();
}

}

class Phone2{
Lock lock = new ReentrantLock();

public void sms(){
lock.lock(); // 细节问题:lock.lock(); lock.unlock(); // lock 锁必须配对,否则就会死在里面
lock.lock();

try {
System.out.println(Thread.currentThread().getName() + "sms");
call();// 这里也有锁
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
lock.unlock();
}
}

public void call(){
lock.lock();

try {
System.out.println(Thread.currentThread().getName() + "call");
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}

执行结果:

1
2
3
4
5
6
Asms
Acall
Bcall

Process finished with exit code 0

两个锁的执行结果相同,当A线程拿到第一个锁之后,就自动拿到下面的锁了,等这个线程的锁全部执行完才会释放锁。

自旋锁

spinlock 自旋锁必须有CAS操作

我们来自定义一个锁测试

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
package com.guocl.Lock;

import java.util.concurrent.atomic.AtomicReference;

/**
* 自旋锁
*/
public class SpinlockDemo {

// int 0
// Thread null
AtomicReference<Thread> atomicReference = new AtomicReference<>();

// 加锁
public void myLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName() + "==> mylock");

//自旋锁 必须有CAS操作
while (!atomicReference.compareAndSet(null, thread)){

}
}

// 解锁
public void myUnLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName() + "==> myUnLock");
atomicReference.compareAndSet(thread, null);
}
}

测试

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
package com.guocl.Lock;

import java.util.concurrent.TimeUnit;

public class SpinlockTest {

public static void main(String[] args) throws InterruptedException {
// ReentrantLock reentrantLock = new ReentrantLock();
// reentrantLock.lock();
// reentrantLock.unlock();

// 底层使用的自旋锁CAS
SpinlockDemo lock = new SpinlockDemo();

new Thread(() -> {
lock.myLock();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.myUnLock();
}
}, "T1").start();

TimeUnit.SECONDS.sleep(1);

new Thread(() -> {
lock.myLock();

try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.myUnLock();
}
}, "T2").start();
}
}

1
2
3
4
5
6
7
8
执行结果:

T1==> mylock
T2==> mylock
T1==> myUnLock
T2==> myUnLock

Process finished with exit code 0

死锁

死锁是什么

死锁测试,怎么排除死锁:

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
package com.guocl.Lock;

import java.util.concurrent.TimeUnit;

public class DeadLockDemo {

public static void main(String[] args) {
String lockA = "lockA";
String lockB = "lockB";

new Thread(new MyThread(lockA, lockB), "T1").start();
new Thread(new MyThread(lockB, lockA), "T1").start();
}

}

class MyThread implements Runnable{

private String lockA;
private String lockB;

public MyThread(String lockA, String lockB){
this.lockA = lockA;
this.lockB = lockB;
}

@Override
public void run() {
synchronized (lockA){
System.out.println(Thread.currentThread().getName() + "lock:" + lockA + "=>get:" + lockB);

try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB){
System.out.println(Thread.currentThread().getName() + "lock:" + lockB + "=>get:" + lockA);
}
}
}
}

解决死锁问题

1、使用 jsp -l 定位进程号

2、使用 jstack 进程号 找到死锁问题

有帮助的话可以来打赏一些或者经常来看看我哦,我在这里等你!