
源码中的枚举值
public enum State {
NEW(新建),
RUNNABLE(可运行状态),
BLOCKED(阻塞状态),
WAITING(等待状态),
TIMED_WAITING(定时等待),
TERMINATED(终止);
}
1.2 wait/sleep的区别
**并发:**同一时刻多个线程在访问同一个资源,多个线程对一个点。
例:春运抢票、电商秒杀。
**并行:**多项工作一起执行,之后再汇总。
例:泡方便面、电水壶烧水,一边撕调料倒入桶中。
1.4 用户线程和守护线程 **用户线程:**平时用到的普通线程,自定义线程。
**守护线程:**运行在后台,是一种特殊的线程,比如垃圾回收机制。
当主线程结束后,用户线程还在运行,JVM存活。
如果没有用户线程,都是守护线程,JVM结束。
二、Lock接口 2.1 Synchronized回顾售票案例
class Ticket {
//票数
private int number = 30;
//操作方法:卖票
public synchronized void sale() {
//判断:是否有票
if(number > 0) {
System.out.println(Thread.currentThread().getName()+":"+(number--)+" "+number);
}
}
}
如果一个代码块被 synchronized 修饰了,当一个线程获取了对应的锁,并执 行该代码块时,其他线程便只能一直等待,等待获取锁的线程释放锁,而这里 获取锁的线程释放锁只会有两种情况: 1)获取锁的线程执行完了该代码块,然后线程释放对锁的占有; 2)线程执行发生异常,此时 JVM 会让线程自动释放锁。
那么如果这个获取锁的线程由于要等待 IO 或者其他原因(比如调用 sleep 方法)被阻塞了,但是又没有释放锁,其他线程便只能干巴巴地等待,试想一 下,这多么影响程序执行效率。 因此就需要有一种机制可以不让等待的线程一直无期限地等待下去(比如只等 待一定的时间或者能够响应中断),通过 Lock 就可以办到。2.2 什么是Lock
Lock 锁实现提供了比使用同步方法和语句可以获得的更广泛的锁操作。它们允许更灵活的结构,可能具有非常不同的属性,并且可能支持多个关联的条件对 象。Lock 提供了比 synchronized 更多的功能。
2.2.1 Lock与Synchronized区别lock()方法是平常使用得最多的一个方法,就是用来获取锁。如果锁已被其他 线程获取,则进行等待。
采用 Lock,必须主动去释放锁,并且在发生异常时,不会自动释放锁。因此一 般来说,使用 Lock 必须在 try{}catch{}块中进行,并且将释放锁的操作放在 finally 块中进行,以保证锁一定被被释放,防止死锁的发生。通常使用 Lock 来进行同步的话,是以下面这种形式去使用的:
Lock lock = new ...;
//上锁
lock.lock();
try{
//处理任务
}catch(Exception ex){
}finally{
//释放锁
lock.unlock();
}
2.2.2.1 newCondition
Lock 锁的 newContition()方法返回 Condition 对象,Condition 类 也可以实现等待/通知模式。
用 notify()通知时,JVM 会随机唤醒某个等待的线程, 使用 Condition 类可以 进行选择性通知, Condition 比较常用的两个方法:
注意:
在调用 Condition 的 await()/signal()方法前,也需要线程持有相关 的 Lock 锁,调用 await()后线程会释放这个锁,在 singal()调用后会从当前 Condition 对象的等待队列中,唤醒 一个线程,唤醒的线程尝试获得锁, 一旦 获得锁成功就继续执行
例:
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void incr() {
lock.lock();
try {
while (num != 0) {
condition.await();
}
num++;
System.out.println(Thread.currentThread().getName() + " :: " + num);
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
2.2.3 ReentrantLock类
ReentrantLock,意思是“可重入锁”。
ReentrantLock 是唯一实现了 Lock 接口的类,并且 ReentrantLock 提供了更 多的方法。
2.2.4 ReadWriteLock接口ReadWriteLock 也是一个接口,在它里面只定义了两个方法:
public interface ReadWriteLock {
Lock readLock();
Lock writeLock();
}
2.2.4.1 ReentrantReadWriteLock实现类
ReentrantReadWriteLock 里面提供了很多丰富的方法,不过最主要的有两个 方法:readLock()和 writeLock()用来获取读锁和写锁。
注意
在性能上来说,如果竞争资源不激烈,两者的性能是差不多的,而当竞争资源 非常激烈时(即有大量线程同时竞争),此时 Lock 的性能要远远优于 synchronized。
三、线程间通信线程间通信的模型有两种:
共享内存
消息传递
以下方式都是基本这两种模 型来实现的
package com.test;
class Ticket {
private int num;
public synchronized void sale() throws InterruptedException {
try {
// 防止虚假唤醒
while (num != 0) {
this.wait();
}
num++;
System.out.println(Thread.currentThread().getName() + " :: " + num);
this.notifyAll();
} finally {
}
}
//减一
public synchronized void decr() throws InterruptedException {
try {
while (num != 1) {
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName() + " :: " + num);
this.notifyAll();
} finally {
}
}
}
public class Test01 {
public static void main(String[] args) {
Ticket test = new Ticket();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
test.sale();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "AA").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
test.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "BB").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
test.decr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "CC").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
test.sale();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "DD").start();
}
}
3.2 采用Lock方案
package com.test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Ticket02 {
private int num;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void incr() {
lock.lock();
try {
while (num != 0) {
condition.await();
}
num++;
System.out.println(Thread.currentThread().getName() + " :: " + num);
// 唤醒线程
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void decr() {
lock.lock();
try {
while (num != 1) {
condition.await();
}
num--;
System.out.println(Thread.currentThread().getName() + " :: " + num);
// 唤醒线程
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class Test02 {
public static void main(String[] args) {
Ticket02 t = new Ticket02();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
t.decr();
}
}
},"aaa").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
t.incr();
}
}
},"bbb").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
t.incr();
}
}
},"ccc").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
t.decr();
}
}
},"ddd").start();
}
}
bbb :: 1 ddd :: 0 bbb :: 1 ddd :: 0 bbb :: 1 ddd :: 0 bbb :: 1 ddd :: 0 bbb :: 1 .....3.3 案例介绍
问题: A 线程打印 5 次 A,B 线程打印 10 次 B,C 线程打印 15 次 C,按照 此顺序循环 10 轮
采用Lock锁实现
package com.test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ShareResource {
private int flag = 1;
private Lock lock = new ReentrantLock();
//声明钥匙A
private Condition c1 = lock.newCondition();
// 声明钥匙B
private Condition c2 = lock.newCondition();
// 声明钥匙C
private Condition c3 = lock.newCondition();
public void print5(int loop) {
// 上锁
lock.lock();
try {
while (flag != 1) {
// 等待
c1.await();
}
// 干活
for (int i = 1; i <= 3; i++) {
System.out.println(Thread.currentThread().getName() + " :: " + i + " :: 轮数:" + loop);
}
// 修改标志位
flag = 2;
// 通知
c2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print10(int loop) {
System.out.println("hhhhhhhhhhhhhhhhhhh");
try {
// 上锁
lock.lock();
while (flag != 2) {
c2.await();
}
// 干活
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " :: " + i + " :: 轮数:" + loop);
}
flag = 3;
c3.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print15(int loop) {
// 上锁
lock.lock();
try {
while (flag != 3) {
c3.await();
}
// 干活
for (int i = 1; i <= 7; i++) {
System.out.println(Thread.currentThread().getName() + " :: " + i + " :: 轮数:" + loop);
}
// 标志位
flag = 1;
// 唤醒c1
c1.signal();
System.out.println();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class Test03 {
public static void main(String[] args) {
ShareResource shareResource = new ShareResource();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
shareResource.print5(i);
}
}
}, "AA").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
shareResource.print10(i);
}
}
}, "BB").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
shareResource.print15(i);
}
}
}, "CC").start();
}
}
打印部分结果:
AA :: 1 :: 轮数:1 AA :: 2 :: 轮数:1 AA :: 3 :: 轮数:1 BB :: 1 :: 轮数:1 BB :: 2 :: 轮数:1 BB :: 3 :: 轮数:1 BB :: 4 :: 轮数:1 BB :: 5 :: 轮数:1 CC :: 1 :: 轮数:1 CC :: 2 :: 轮数:1 CC :: 3 :: 轮数:1 CC :: 4 :: 轮数:1 CC :: 5 :: 轮数:1 CC :: 6 :: 轮数:1 CC :: 7 :: 轮数:1 ...
总结
synchronized实现同步的基础:Java中的每一个对象都可以作为锁,
具体表现形式为以下3种形式:
首先编写一个非线程安全的集合ArrayList,来实现多线程插入数据。
package com.listSync;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class ThreadOfList {
public static void main(String[] args) {
// 创建ArrayList集合
List list = new ArrayList<>();
final List list = new CopyOnWriteArrayList<>();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
int finalI = i;
new Thread(new Runnable() {
@Override
public void run() {
// 向集合中添加元素
list.add(UUID.randomUUID().toString().substring(0, 10));
// 从集合中获取元素
System.out.println(list);
list.remove(0);
}
}, String.valueOf(i)).start();
}
long end = System.currentTimeMillis();
}
}
运行后,会报 java.util.ConcurrentModificationException
我们如何去解决 List 类型的线程安全问题?
3.2 解决集合线程安全问题 3.2.1 VectorVector 是矢量队列,它是 JDK1.0 版本添加的类。继承于 AbstractList,实现 了 List, RandomAccess, Cloneable 这些接口。 Vector 继承了 AbstractList, 实现了 List;所以,它是一个队列,支持相关的添加、删除、修改、遍历等功 能。 Vector 实现了 RandmoAccess 接口,即提供了随机访问功能。 RandmoAccess 是 java 中用来被 List 实现,为 List 提供快速访问功能的。在 Vector 中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访 问。 Vector 实现了 Cloneable 接口,即实现 clone()函数。它能被克隆。
代码实现
package com.listSync;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class ThreadOfList {
public static void main(String[] args) {
// 创建ArrayList集合
// List list = new ArrayList<>();
// Vector解决集合
List list = new Vector<>();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
int finalI = i;
new Thread(new Runnable() {
@Override
public void run() {
// 向集合中添加元素
list.add(UUID.randomUUID().toString().substring(0, 10));
// 从集合中获取元素
System.out.println(list);
}
}, String.valueOf(i)).start();
}
long end = System.currentTimeMillis();
}
}
查看Vector的add方法
public synchronized boolean add(E e) {
modCount++;
add(e, elementData, elementCount);
return true;
}
add 方法被 synchronized 同步修辞,线程安全!因此没有并发异常
3.2.2 CollectionsCollections 提供了方法 synchronizedList 保证 list 是同步线程安全的
public class ThreadOfList {
public static void main(String[] args) {
// 1、创建ArrayList集合
// List list = new ArrayList<>();
// 2、Vector解决集合
// List list = new Vector<>();
// 3、使用Collections中的synchronizedList()方法
List list = Collections.synchronizedList(new ArrayList());
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
int finalI = i;
new Thread(new Runnable() {
@Override
public void run() {
// 向集合中添加元素
list.add(UUID.randomUUID().toString().substring(0, 10));
// 从集合中获取元素
System.out.println(list);
}
}, String.valueOf(i)).start();
}
long end = System.currentTimeMillis();
}
}
查看源码可知
public static3.2.3 CopyOnWriteArrayList(重点)List synchronizedList(List list) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list) : new SynchronizedList<>(list)); }
特点:
当我们往一个容器添加元素的时候,不直接往当前容器添加,而是先将当前容 器进行 Copy,复制出一个新的容器,然后新的容器里添加元素,添加完元素 之后,再将原容器的引用指向新的容器。 这时候会抛出来一个新的问题,也就是数据不一致的问题。如果写线程还没来 得及写会内存,其他的线程就会读到了脏数据。
具体实现:
package com.listSync;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class ThreadOfList {
public static void main(String[] args) {
List list = new CopyOnWriteArrayList<>();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
int finalI = i;
new Thread(new Runnable() {
@Override
public void run() {
// 向集合中添加元素
list.add(UUID.randomUUID().toString().substring(0, 10));
// 从集合中获取元素
System.out.println(list);
}
}, String.valueOf(i)).start();
}
long end = System.currentTimeMillis();
}
}
原因分析
从“动态数组”和“线程安全”两个方面进一步对 CopyOnWriteArrayList 的原理进行说明。
动态数组
1、它内部有个“volatile 数组”(array)来保持数据。在“添加/修改/删除”数据 时,都会新建一个数组,并将更新后的数据拷贝到新建的数组中,最后再将该 数组赋值给“volatile 数组”, 这就是它叫做 CopyOnWriteArrayList 的原因。 2、由于它在“添加/修改/删除”数据时,都会新建数组,所以涉及到修改数据的 操作,CopyOnWriteArrayList 效率很低;但是单单只是进行遍历查找的话, 效率比较高。
线程安全机制
通过 volatile 和互斥锁来实现的。 o 通过“volatile 数组”来保存数据的。一个线程读取 volatile 数组时,总能看 到其它线程对该 volatile 变量最后的写入;就这样,通过 volatile 提供了“读 取到的数据总是最新的”这个机制的保证。 o 通过互斥锁来保护数据。在“添加/修改/删除”数据时,会先“获取互斥锁”, 再修改完毕之后,先将数据更新到“volatile 数组”中,然后再“释放互斥 锁”,就达到了保护数据的目的。本章小结
| 线程不安全 | 线程安全 |
|---|---|
| ArrayList | Vector、Collections.synchronizedList( List list)、CopyOnWriteArrayList( ) |
| HashMap | ConcurrentHashMap( )、Collections.synchronizedMap(Map map )、Hashtable |
| HashSet | Collections.synchronizedSet(Set set)、CopyOnWriteArraySet( ); |
集合类型中存在线程安全与线程不安全的两种,
常见例如:
ArrayList ----- Vector
HashMap -----HashTable
但是以上都是通过 synchronized 关键字实现,效率较低。
CopyOnWriteArrayList CopyOnWriteArraySet 类型,通过动态数组与线程安 全个方面保证线程安全四、多线程锁 4.1 示例
package com.synchronizedCase;
class Phone {
public synchronized void sendEmail() throws InterruptedException {
//睡眠4秒
Thread.sleep(4000);
System.out.println("-------sendEmail");
}
// j
public synchronized void sendMsg() {
System.out.println("-------sendMsg");
}
//未加锁的方法
public void hello(){
System.out.println("------Hello");
}
}
public class SyncFor8 {
public static void main(String[] args) throws InterruptedException {
Phone phone = new Phone();
Phone phone2 = new Phone();
new Thread(new Runnable() {
@Override
public void run() {
try {
phone.sendEmail();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
// Thread.sleep(100);
new Thread(new Runnable() {
@Override
public void run() {
phone.sendMsg();
}
}).start();
}
}
打印输出结果:
-------sendEmail -------sendMsg
可以得出以下结论:
定义:多个线程按照申请锁的顺序去获得锁,线程会直接进入队列(先进先出FIFO)去排队,永远都是队列的第一位才能得到锁。
优点:所有的线程都能得到资源,不会饿死在队列中。
缺点:吞吐量会下降很多,队列里面除了第一个线程,其他的线程都会阻塞,CPU唤醒阻塞线程的开销会很大。
4.2.2 非公平锁 定义:多个线程去获取锁的时候,会直接去尝试获取,获取不到,再去进入等待队列,如果能获取到,就直接获取到锁。
优点:可以减少CPU唤醒线程的开销,整体的吞吐效率会高点,CPU也不必取唤醒所有线程,会减少唤起线程的数量。
缺点:你们可能也发现了,这样可能导致队列中间的线程一直获取不到锁或者长时间获取不到锁,导致饿死。
4.3 死锁定义:两个或者两个以上进程在执行过程中,因为争夺资源而造成一种互相等待的现象,如果没有外力的干涉,他们再无法下载。
4.3.1 产生死锁的原有public class Deadlock {
static Object a = new Object();
static Object b = new Object();
public static void main(String[] args) throws InterruptedException {
//线程A
new Thread(() -> {
synchronized (a) {
System.out.println(Thread.currentThread().getName() + "持有锁a,试图获取锁b");
synchronized (b) {
System.out.println(Thread.currentThread().getName() + "获取锁b");
}
}
}, "AA").start();
//线程B
new Thread(() -> {
synchronized (b) {
System.out.println(Thread.currentThread().getName() + "持有锁b,试图获取锁a");
synchronized (a) {
System.out.println(Thread.currentThread().getName() + "获取锁a");
}
}
}, "BB").start();
}
}
五、Callable或Future接口
特点:
当 call()方法完成时,结果必须存储在主线程已知的对象中,以便主线程可 以知道该线程返回的结果。为此,可以使用 Future 对象。
将 Future 视为保存结果的对象–它可能暂时不保存结果,但将来会保存(一旦 Callable 返回)。
Future 基本上是主线程可以跟踪进度以及其他线程的结果的 一种方式。要实现此接口,必须重写 5 种方法,
这里列出了重要的方法,如下:
public boolean cancel(boolean mayInterrupt):用于停止任务。
如果尚未启动,它将停止任务。如果已启动,则仅在 mayInterrupt 为 true 时才会中断任务。
public Object get()抛出 InterruptedException,ExecutionException: 用于获取任务的结果。
如果任务完成,它将立即返回结果,否则将等待任务完成,然后返回结果。
public boolean isDone()
如果任务完成,则返回 true,否则返回 false 可以看到 Callable 和 Future 做两件事-Callable 与 Runnable 类似,因为它封装了要在另一个线程上运行的任务,而 Future 用于存储从另一个线程获得的结 果。实际上,future 也可以与 Runnable 一起使用。
介绍:
Java 库具有具体的 FutureTask 类型,该类型实现 Runnable 和 Future,并方 便地将两种功能组合在一起。 可以通过为其构造函数提供 Callable 来创建 FutureTask。然后,将 FutureTask 对象提供给 Thread 的构造函数以创建 Thread 对象。因此,间接地使用 Callable 创建线程。
核心原理:
在主线程中需要执行比较耗时的操作时,但又不想阻塞主线程,可以把这些作业交给Fucture对象在后台完成。
示例:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyThread02 implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程进入了run方法。");
}
}
class MyThread03 implements Callable {
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName() + "线程进入了call方法,现在开始睡觉。");
Thread.sleep(3000);
return 1024;
}
}
public class Demo02 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable callable = new MyThread03();
Runnable runnable = new MyThread02();
FutureTask futureTask = new FutureTask(callable);
new Thread(futureTask, "线程二").start();
for (int i = 0; i < 3; i++) {
Integer integer = futureTask.get();
System.out.println(integer);
}
new Thread(runnable, "线程一").start();
}
}
5.3 小结
JUC 中提供了三种常用的辅助类,通过这些辅助类可以很好的解决线程数量过多时 Lock 锁的频繁操作。这三种辅助类为:
示例:
package jucUtils;
import java.util.concurrent.CountDownLatch;
public class MyCountDownLatch {
public static void main(String[] args) throws InterruptedException {
CountDownLatch count = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + "离开了");
count.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
System.out.println("主线程睡觉");
// 阻塞主线程
count.await();
System.out.println(Thread.currentThread().getName() + "锁门了");
}
}
//结果打印
6.2 循环栅栏 CyclicBarrier
CyclicBarrier 看英文单词可以看出大概就是循环阻塞的意思,在使用中 CyclicBarrier 的构造方法第一个参数是目标障碍数,每次执行 CyclicBarrier 一 次障碍数会加一,如果达到了目标障碍数,才会执行 cyclicBarrier.await()之后 的语句。可以将 CyclicBarrier 理解为加 1 操作。
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class MyCyclicBarrier {
private static final int NUMBER = 7;
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER, new Runnable() {
@Override
public void run() {
System.out.println("集齐" + NUMBER + "颗龙珠,现在召唤神龙!");
}
});
for (int i = 1; i < 8; i++) {
new Thread(() -> {
try {
if (Thread.currentThread().getName().equals("龙珠4号")) {
System.out.println("正在抢夺龙珠4号");
Thread.sleep(3000);
System.out.println("龙珠3号抢夺成功了,");
} else {
System.out.println(Thread.currentThread().getName() + "收集到了。");
}
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}, "龙珠" + i + "号").start();
}
}
}
//打印结果
6.3 信号灯 Semaphore
Semaphore 的构造方法中传入的第一个参数是最大信号量(可以看成最大线 程池),每个信号量初始化为一个最多只能分发一个许可证。使用 acquire 方 法获得许可证,release 方法释放许可。
示例:
场景: 抢车位, 6 部汽车 3 个停车位
package jucUtils;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class MySemaphore {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 5; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"号车获取到了车位。");
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + "号车离开了停车场。....");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
//打印结果
七、读写锁
7.1 介绍
JAVA 的并发包提供了读写锁 ReentrantReadWriteLock, 它表示两个锁,一个是读操作相关的锁,称为共享锁;一个是写相关的锁,称 为排他锁。
线程进入读锁的前提条件
1、没有其他线程的写锁。 2、没有写请求, 或者==有写请求,但调用线程和持有锁的线程是同一个(可重入锁)。
线程进入写锁的前提条件
• 没有其他线程的读锁 • 没有其他线程的写锁
3.读写锁的三个重要的特征:
(1)公平选择性:支持非公平(默认)和公平的锁获取方式,吞吐量还是非公平优于公平。 (2)重进入:读锁和写锁都支持线程重进入。 (3)锁降级:遵循获取写锁、获取读锁再释放写锁的次序,写锁能够降级成为读锁。7.2 ReentrantReadWriteLock 7.2.1 入门案例
package readwrite;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class MyReadWrite {
//创建HashMap集合
private volatile Map map = new HashMap<>();
//创建读写锁对象
private ReadWriteLock rwlock = new ReentrantReadWriteLock();
//写操作
public void put(String key, Object obj) {
//添加写锁
rwlock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " 正在写操作" + key);
//暂停一会,模拟写过程耗时
TimeUnit.MILLISECONDS.sleep(300);
//放数据
map.put(key, obj);
System.out.println(Thread.currentThread().getName() + " 写完了" + key);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放锁资源
rwlock.writeLock().unlock();
}
}
public Object get(String key) {
Object result = null;
//添加读锁
rwlock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " 正在读取操作" + key);
//暂停一会,模拟读取数据耗时
TimeUnit.MILLISECONDS.sleep(300);
result = map.get(key);
System.out.println(Thread.currentThread().getName() + " 取完了" + key);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 释放读锁资源
rwlock.readLock().unlock();
}
return result;
}
public static void main(String[] args) {
MyReadWrite readWrite = new MyReadWrite();
//写数据
for (int i = 1; i < 6; i++) {
final int num = i;
new Thread(() -> {
readWrite.put(num + "", num);
}, String.valueOf(num)).start();
}
//读数据
for (int i = 1; i < 6; i++) {
final int num = i;
new Thread(() -> {
readWrite.get(num + "");
}, String.valueOf(num)).start();
}
}
}
//结果展示
7.3 小结
获取写锁----->获取读锁----->释放写锁------>释放读锁。完成锁的降级。
原因分析:
当线程获取读锁的时候,可能有其他线程同时也在持有读锁,因此不能把 获取读锁的线程“升级”为写锁; 而对于获得写锁的线程,它一定独占了读写锁, 因此可以继续让它获取读锁,当它同时获取了写锁和读锁后,还可以先释放写锁继续持有读锁,这样一个写锁就“降级”为了读锁。八 、阻塞队列 8.1 BlockingQueue 简介
阻塞队列,顾名思义,首先它是一个队列, 通过一个共享的队列,可以使得数据 由队列的一端输入,从另外一端输出;
试图从空的队列中获取元素的线程将会被阻塞,直到其他线程往空的队列插入新的元素
试图向已满的队列中添加新元素的线程将会被阻塞,直到其他线程从队列中移除一个或多个元素或完全清空,使队列变得空闲起来并后续新增。
常见队列有以下两种:
为什么要使用阻塞队列?
我们不需要关心什么时候需要阻塞线程,什么时候需要唤醒线程,因为这一切BlockingQueue都给我们做好了。
package queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public class MyBlockingQueue {
public static void main(String[] args) throws InterruptedException {
//创建阻塞队列
BlockingQueue blockingQueue = new ArrayBlockingQueue(3);
//第一组
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
blockingQueue.clear();
// 第二组
System.out.println("第二组");
System.out.println(blockingQueue.offer("A"));
System.out.println(blockingQueue.offer("B"));
System.out.println(blockingQueue.offer("C"));
System.out.println(blockingQueue.offer("D"));
System.out.println(blockingQueue.poll());
blockingQueue.clear();
// 第三组
System.out.println("第三组");
blockingQueue.put("1");
blockingQueue.put("2");
blockingQueue.put("3");
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
//System.out.println(blockingQueue.take());
blockingQueue.clear();
// 第四组
System.out.println("第四组");
blockingQueue.offer("1", 3, TimeUnit.SECONDS);
blockingQueue.offer("2", 3, TimeUnit.SECONDS);
blockingQueue.offer("3", 3, TimeUnit.SECONDS);
blockingQueue.offer("4", 3, TimeUnit.SECONDS);
System.out.println(blockingQueue.poll(3,TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(3,TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(3,TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(3,TimeUnit.SECONDS));
}
}
8.2.4 常见的BlockingQueue
在 concurrent 包发布以前,在多线程环境下, 我们每个程序员都必须去自己控制这些细节,尤其还要兼顾效率和线程安全, 而这会给我们的程序带来不小的复杂度。使用后我们不需要关心什么时候需要 阻塞线程,什么时候需要唤醒线程,因为这一切 BlockingQueue 都给你一手 包办了。九、线程池 9.1 简介
线程池是一种线程使用模式。线程过多会带来调度的开销,进而影响缓存局部性和整体性能。 而线程池维护着多个线程,等待着监督管理 者分配可并发执行的任务。这避免了在处理短时间任务时创建与销毁线程的代 价。线程池不仅能够保证内核的充分利用,还能防止过分调度。9.2 优势与特点
优势:
线程池做的工作只要是控制运行的线程数量,处理过程中将任 务放入队列,然后在线程创建后启动这些任务,如果线程数量超过了最大数量, 超出数量的线程排队等候,等其他线程执行完毕,再从队列中取出任务来执行。
特点:
作用:创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
特点:
场景:
创建方式
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
9.4.2 newFixedThreadPool(常用)
作用:
创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这 些线程。在任意点,在大多数线程会处于处理任务的活动状态。如果在所有线 程处于活动状态时提交附加任务,则在有可用线程之前,附加任务将在队列中 等待。如果在关闭前的执行期间由于失败而导致任何线程终止,那么一个新线 程将代替它执行后续的任务(如果需要)。在某个线程被显式地关闭之前,池 中的线程将一直存在。
特征:
场景:
适用于可以预测线程数量的业务中,或者服务器负载较重,对线程数有严格限制的场景。
创建方式:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}
9.4.3 newSingleThreadExecutor(常用)
作用:
创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该 线程。
(注意,如果因为在关闭前的执行期间出现失败而终止了此单个线程, 那么如果需要,一个新线程将代替它执行后续的任务)。可保证顺序地执行各 个任务,并且在任意给定的时间不会有多个线程是活动的。与其他等效的 newFixedThreadPool 不同,可保证无需重新配置此方法所返回的执行程序即 可使用其他的线程。
特征:
场景:
适用于需要保证顺序执行各个任务,并且在任意时间点,不会同时有多个 线程的场景。
创建方式:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}
9.4.4 newScheduleThreadPool(了解)
作用:
线程池支持定时以及周期期性执行任务,创建一个 corePoolSize 为传入参 数,最大线程数为整形的最大数的线程池**。
特征:
场景:
适用于需要多个后台线程执行周期任务的场景。
创建方式:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}
9.4.5 newWorkStealingPool
简介:
jdk1.8 提供的线程池,底层使用的是 ForkJoinPool 实现,创建一个拥有多个任务队列的线程池,可以减少连接数,创建当前可用 cpu 核数的线程来并行执 行任务。
创建方式:
public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool
(parallelism,
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}
9.5 线程池参数说明
9.5.1 常用参数(重点)
线程池中,有三个重要的参数,决定影响了拒绝策略:
当提交任务数大于 corePoolSize 的时候,会优先将任务放到 workQueue 阻 塞队列中。当阻塞队列饱和后,会扩充线程池中线程数,直到达到maximumPoolSize 最大线程数配置。此时,再多余的任务,则会触发线程池 的拒绝策略了。
9.5.2 总结当提交的任务数大于(workQueue.size( ) + maximumPoolSize ),就会触发线程池的拒绝策略。
9.5.3 拒绝策略(重点) 当触发拒绝策略,只要线程池没有关闭的话,则使用调用 线程直接运行任务。一般并发比较小,性能要求不高,不允许失败。但是,由 于调用者自己运行任务,如果任务提交速度过快,可能导致程序阻塞,性能效 率上必然的损失较大。
丢弃任务,并抛出拒绝执行 RejectedExecutionException 异常 信息。线程池默认的拒绝策略。必须处理好抛出的异常,否则会打断当前的执 行流程,影响后续的任务执行。
直接丢弃,其他啥都没有。
当触发拒绝策略,只要线程池没有关闭的话,丢弃阻塞 队列 workQueue 中最老的一个任务,并将新任务加入。
9.6 线程池底层原理执行流程
在创建了线程池后,线程池中的线程数为零。
当调用 execute()方法添加一个请求任务时,线程池会做出如下判断:
如 果正在运行的线程数量小于 corePoolSize,那么马上创建线程运行这个任务。
如果正在运行的线程数量大于或等于 corePoolSize,那么将这个任务放入 队列;
如果这个时候队列满了且正在运行的线程数量还小于 maximumPoolSize,那么还是要创建非核心线程立刻运行这个任务;
如 果队列满了且正在运行的线程数量大于或等于 maximumPoolSize,那么线程 池会启动饱和拒绝策略来执行。
当一个线程完成任务时,它会从队列中取下一个任务来执行。
. 当一个线程无事可做超过一定的时间(keepAliveTime)时,线程会判断:
如果当前运行的线程数大于 corePoolSize,那么这个线程就被停掉。
所以线程池的所有任务完成后,它最终会收缩到 corePoolSize 的大小。
示例
package pool;
import java.util.concurrent.*;
//自定义线程池
public class CustomerThreadPool {
public static void main(String[] args) {
ExecutorService executor = new ThreadPoolExecutor(
2,//核心线程数
5,//最大线程数(包含核心线程数)
2L,//空闲线程存活时间
TimeUnit.SECONDS,//时间单位
new ArrayBlockingQueue<>(3),//阻塞队列,存放提交但未执行任务的队列
Executors.defaultThreadFactory(),//创建线程的工厂类:可以省略
new ThreadPoolExecutor.AbortPolicy()//等待队列满后的拒绝策略:可省略
);
// 8个顾客请求
try {
for (int i = 1; i <= 8; i++) {
//执行
executor.execute(()->{
System.out.println(Thread.currentThread().getName() + " 办理业务。");
});
}
} finally {
executor.shutdown();
}
}
}
//结果打印
9.7 总结
Fork/Join 它可以将一个大的任务拆分成多个子任务进行并行处理,最后将子 任务结果合并成最后的计算结果,并进行输出。Fork/Join 框架要完成两件事 情:
Fork:把一个复杂任务进行分拆,大事化小 Join:把分拆任务的结果进行合并
任务分割:
首先 Fork/Join 框架需要把大的任务分割成足够小的子任务,如果 子任务比较大的话还要对子任务进行继续分割。
执行任务并合并结果:
分割的子任务分别放到双端队列里,然后几个启动线程 分别从双端队列里获取任务执行。子任务执行完的结果都放在另外一个队列里, 启动一个线程从队列里取数据,然后合并这些数据。
在 Java 的 Fork/Join 框架中,使用两个类完成上述操作
ForkJoinTask :
我们要使用 Fork/Join 框架,首先需要创建一个 ForkJoin 任务。 该类提供了在任务中执行 fork 和 join 的机制。通常情况下我们不需要直接集 成 ForkJoinTask 类,只需要继承它的子类,Fork/Join 框架提供了两个子类:
ForkJoinPool :
ForkJoinTask 需要通过 ForkJoinPool 来执行
RecursiveTask:
继承后可以实现递归(自己调自己)调用的任务。
Fork/Join 框架的实现原理
ForkJoinPool 由 ForkJoinTask 数组和 ForkJoinWorkerThread 数组组成,】 ForkJoinTask 数组负责将存放以及将程序提交给 ForkJoinPool, 而 ForkJoinWorkerThread 负责执行这些任务。10.2 Fork 方法
分支合并池 类比 = > 线程池。
**tips:**idea的快捷键(Ctrl + Shift + Alt + U)。
递归任务:继承后可以实现递归调用的任务。
Fork 方法的实现原理
当我们调用 ForkJoinTask 的 fork 方法时,程序会把 任务放在 ForkJoinWorkerThread 的 pushTask 的 workQueue 中,异步地执行这个任务,然后立即返回结果
public final ForkJoinTaskfork() { Thread t; if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ((ForkJoinWorkerThread)t).workQueue.push(this); else ForkJoinPool.common.externalPush(this); return this; }
pushTask 方法把当前任务存放在 ForkJoinTask 数组队列里。然后再调用 ForkJoinPool 的 signalWork()方法唤醒或创建一个工作线程来执行任务。代 码如下:
final void push(ForkJoinTask> task) {
ForkJoinTask>[] a; ForkJoinPool p;
int b = base, s = top, n;
if ((a = array) != null) { // ignore if queue removed
int m = a.length - 1; // fenced write for task visibility
U.putOrderedObject(a, ((m & s) << ASHIFT) + ABASE, task);
U.putOrderedInt(this, QTOP, s + 1);
if ((n = s - b) <= 1) {
if ((p = pool) != null)
p.signalWork(p.workQueues, this);
}
else if (n >= m)
growArray();
}
}
10.3 join方法
Join 方法的主要作用是阻塞当前线程并等待获取结果。让我们一起看看 ForkJoinTask 的 join 方法的实现,代码如下:
public final V join() {
int s;
if ((s = doJoin() & DONE_MASK) != NORMAL)
reportException(s);
return getRawResult();
}
它首先调用 doJoin 方法,通过 doJoin()方法得到当前任务的状态来判断返回 什么结果,任务状态有 4 种:
如果任务状态是已完成,则直接返回任务结果。
如果任务状态是被取消,则直接抛出 CancellationException 。
如果任务状态是抛出异常,则直接抛出对应的异常。
让我们分析一下 doJoin 方法的实现
private int doJoin() {
int s; Thread t; ForkJoinWorkerThread wt; ForkJoinPool.WorkQueue w;
return (s = status) < 0 ? s :
((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
(w = (wt = (ForkJoinWorkerThread)t).workQueue).
tryUnpush(this) && (s = doExec()) < 0 ? s :
wt.pool.awaitJoin(w, this, 0L) :
externalAwaitDone();
}
final int doExec() {
int s; boolean completed;
if ((s = status) >= 0) {
try {
completed = exec();
} catch (Throwable rex) {
return setExceptionalCompletion(rex);
}
if (completed)
s = setCompletion(NORMAL);
}
return s;
}
在doJoin( )方法流程如下:
首先通过查看任务的状态,看任务是否已经执行完成,如果执行完成,则直接 返回任务状态;
如果没有执行完,则从任务数组里取出任务并执行。
如果任务顺利执行完成,则设置任务状态为 NORMAL,如果出现异常,则记 录异常,并将任务状态设置为 EXCEPTIONAL。
ForkJoinTask 在执行的时候可能会抛出异常,但是我们没办法在主线程里直接 捕获异常,所以 ForkJoinTask 提供了 isCompletedAbnormally( )方法来检查 任务是否已经抛出异常或已经被取消了,并且可以通过 ForkJoinTask 的 getException 方法获取异常。
getException( ) 方法返回 Throwable 对象,如果任务被取消了则返回 CancellationException。如果任务没有完成或者没有抛出异常则返回 null。
10.5 示例场景: 生成一个计算任务,计算 1+2+3…+100,每 10 个数切分一个 子任务
package forkjoin; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; class MyTask extends RecursiveTask十一、CompletableFuture(异步编程) 11.1 简介{ public static final Integer VALUE = 10; private int begin; private int end; private int result; public MyTask(int begin, int end) { this.begin = begin; this.end = end; } @Override protected Integer compute() { //判断相加两个数值是否大于10 if ((end - begin) <= VALUE) { for (int i = begin; i <= end; i++) { result += i; } } else { // 进一步做拆分 int mid = (end + begin) >> 1; MyTask task01 = new MyTask(begin, mid); MyTask task02 = new MyTask(mid + 1, end); task01.fork(); task02.fork(); // 合并结果 result = task01.join() + task02.join(); } return result; } } public class MyForkJoin { public static void main(String[] args) throws ExecutionException, InterruptedException { //创建task对象 MyTask myTask = new MyTask(0, 100); //创建分支合并池对象 ForkJoinPool forkJoinPool = new ForkJoinPool(); ForkJoinTask forkJoinTask = forkJoinPool.submit(myTask); // 获取最终合并之后结果 Integer result = forkJoinTask.get(); System.out.println("result = " + result); // 关闭池对象 forkJoinPool.shutdown(); } }
CompletableFuture 在 Java 里面被用于异步编程,异步通常意味着非阻塞, 可以使得我们的任务单独运行在与主线程分离的其他线程中,并且通过回调可 以在主线程中得到异步任务的执行状态,是否完成,和是否异常等信息。
CompletableFuture 实现了 Future, CompletionStage 接口,实现了 Future 接口就可以兼容现在有线程池框架,而 CompletionStage 接口才是异步编程 的接口抽象,里面定义多种异步方法,通过这两者集合,从而打造出了强大的 CompletableFuture 类。
11.2 Future 与 CompletableFuture Futrue 在 Java 里面,通常用来表示一个异步任务的引用,比如我们将任务提 交到线程池里面,然后我们会得到一个 Futrue,在 Future 里面有 isDone 方 法来 判断任务是否处理结束,还有 get 方法可以一直阻塞直到任务结束然后获 取结果,但整体来说这种方式,还是同步的,因为需要客户端不断阻塞等待或 者不断轮询才能知道任务是否完成。
Future 的主要缺点如下:
我提交了一个任务,但是执行太慢了,我通过其他路径已经获取到了任务结果, 现在没法把这个任务结果通知到正在执行的线程,所以必须主动取消或者一直 等待它执行完成
通过 Future 的 get 方法会一直阻塞到任务完成,但是想在获取任务之后执行 额外的任务,因为 Future 不支持回调函数,所以无法实现这个功能
对于 Future 的执行结果,我们想继续传到下一个 Future 处理使用,从而形成 一个链式的 pipline 调用,这在 Future 中是没法实现的。
比如我们有 10 个 Future 并行执行,我们想在所有的 Future 运行完毕之后, 执行某些函数,是没法通过 Future 实现的。
Future 的 API 没有任何的异常处理的 api,所以在异步运行时,如果出了问题 是不好定位的。11.3 CompletableFuture 11.3.1 使用 CompletableFuture
场景:主线程里面创建一个 CompletableFuture,然后主线程调用 get 方法会 阻塞,最后我们在一个子线程中使其终止。
package completable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class MyCompletableFuture02 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture completableFuture = new CompletableFuture<>();
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + "子线程开始干活了。");
//子线程睡眠5秒
TimeUnit.SECONDS.sleep(2);
// 在子线程中完成主线程
completableFuture.complete("success");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "SubA").start();
// 在主线程调用get方法阻塞
System.out.println("主线程调用get方法获取结果为:"+completableFuture.get());
System.out.println("主线程完成。");
}
}
//结果打印
11.3.2 没有返回值的异步任务
package completable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class MyCompletableFutureVoid {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("主线程开始。");
//运行一个没有返回值的异步任务
CompletableFuture future = CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
try {
System.out.println("子线程启动干活。");
//休眠2秒
TimeUnit.SECONDS.sleep(2);
System.out.println("子线程完成。");
} catch (Exception e) {
e.printStackTrace();
}
}
});
// 主线程阻塞
future.get();
System.out.println("Main over");
}
}
//结果打印
10.3.3 有返回值的异步任务
package completable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
public class MyCompletableFutureObject {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("主线程开始");
// 运行一个有返回值的异步任务
CompletableFuture future = CompletableFuture.supplyAsync(new Supplier() {
@Override
public String get() {
try {
System.out.println("子线程开始任务");
TimeUnit.SECONDS.sleep(3);
} catch (Exception e) {
e.printStackTrace();
}
return "sub子线程执行完毕了。";
}
});
// 主线程阻塞
String s = future.get();
System.out.println("主线程结束,子线程的结果为:" + s);
}
}
//结果打印
11.3.4 线程依赖
当一个线程依赖另一个线程时,可以使用 thenApply 方法来把这两个线程串行化。
package completable;
import com.sun.org.apache.xerces.internal.impl.dv.xs.IntegerDV;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
public class MyThreadDependency {
private static Integer num = 10;
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("主线程开始");
CompletableFuture future = CompletableFuture.supplyAsync(new Supplier() {
@Override
public Integer get() {
try {
System.out.println("加10任务开始");
num += 10;
} catch (Exception e) {
e.printStackTrace();
}
return num;
}
}).thenApply(integer -> {
return num * num;
});
Integer integer = future.get();
System.out.println("主线程结束,子线程的结果为:" + integer);
}
}
//结果打印
11.3.5 消费处理结果
thenAccept 消费处理结果, 接收任务的处理结果,并消费处理,无返回结果。
package completable;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
public class MyCompletableThenAccept {
public static Integer num = 10;
public static void main(String[] args) {
System.out.println("主线程开始。");
CompletableFuture.supplyAsync(() -> {
try {
System.out.println("加10任务开始");
num += 10;
} catch (Exception e) {
e.printStackTrace();
}
return num;
}).thenApply(integer -> {
return num * num;
}).thenAccept(new Consumer() {
@Override
public void accept(Integer integer) {
System.out.println("子线程全部处理完成,最后调用了accept方法,结果为: " + integer);
}
});
}
}
//打印结果
11.3.7 异常处理
exceptionally 异常处理,出现异常时触发。
package completable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
public class MyCompletableException {
public static Integer num = 10;
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("主线程");
CompletableFuture future = CompletableFuture.supplyAsync(new Supplier() {
@Override
public Integer get() {
int i = 1 / 0;
System.out.println("加10任务开始");
num += 10;
return num;
}
}).exceptionally(ex -> {
System.out.println(ex.getMessage());
return -1;
});
System.out.println(future.get());
}
}
//打印结果
handle 类似于 thenAccept/thenRun 方法,是最后一步的处理调用,但是同时可以处理异常
package completable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
public class MyCompletableExceptionHandler {
public static Integer num = 10;
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("主线程执行。");
CompletableFuture future = CompletableFuture.supplyAsync(new Supplier() {
@Override
public Integer get() {
System.out.println("加10任务开始");
num += 10;
return num;
}
}).thenApply((i) -> {
int k=10/0;
return num * num;
}).handle((i, ex) -> {
if (ex != null) {
System.out.println("发生了异常,内容为:" + ex.getMessage());
return -1;
} else {
return i;
}
});
System.out.println(future.get());
}
}
//抛出异常结果
//未抛出异常
11.3.8 结果合并
thenCompose 合并两个有依赖关系的 CompletableFutures 的执行结果
package completable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
public class MyCompletableCompose {
public static Integer num = 10;
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("主线程开始");
//第一步 加10
CompletableFuture future = CompletableFuture.supplyAsync(new Supplier() {
@Override
public Integer get() {
System.out.println("加10任务开始。");
num += 10;
return num;
}
});
// 合并
CompletableFuture future1 = future.thenCompose(i ->
CompletableFuture.supplyAsync(() -> {
return i + 1;
}));
System.out.println("num = "+future.get());
System.out.println("i = "+future1.get());
}
}
//结果打印
thenCombine 合并两个没有依赖关系的 CompletableFutures 任务
package completable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiFunction;
public class MyCompletableCombine {
private static Integer num = 10;
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("主线程开始");
//加10
CompletableFuture c1 = CompletableFuture.supplyAsync(() -> {
System.out.println("加10任务开始");
return num += 10;
});
//乘10
CompletableFuture c2 = CompletableFuture.supplyAsync(() -> {
System.out.println("加10后,乘以10任务开始");
return num *= 10;
});
// 合并结果
CompletableFuture
合并多个任务的结果 allOf 与 anyOf allOf:
allOf:一系列独立的 future 任务,等其所有的任务执行完后做一些事情。
package completable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
public class MyCompletableAllOf {
private static Integer num = 10;
public static void main(String[] args) {
System.out.println("Main begin");
List list = new ArrayList<>();
//加10任务开始
CompletableFuture c1 = CompletableFuture.supplyAsync(() -> {
System.out.println("加10任务开始。");
return num += 10;
});
list.add(c1);
//乘10任务开始
CompletableFuture c2 = CompletableFuture.supplyAsync(() -> {
System.out.println("乘10任务开始。");
return num *= 10;
});
list.add(c2);
//减10任务开始
CompletableFuture c3 = CompletableFuture.supplyAsync(() -> {
System.out.println("减10任务开始。");
return num -= 10;
});
list.add(c3);
//除10任务开始
CompletableFuture c4 = CompletableFuture.supplyAsync(() -> {
System.out.println("除10任务开始。");
return num /= 10;
});
list.add(c4);
// 多任务合并
List collect = list.stream().map(CompletableFuture::join).collect(Collectors.toList());
System.out.println("collect = " + collect);
}
}
//结果打印
anyOf: 只要在多个 future 里面有一个返回,整个任务就可以结束,而不需要等到每一个 future 结束。
package completable;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class MyCompletableAnyOf {
private static Integer num = 10;
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("Main Begin");
CompletableFuture[] futures = new CompletableFuture[4];
//加10操作
CompletableFuture c1 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("加10任务开始。");
return num += 10;
} catch (InterruptedException e) {
e.printStackTrace();
return 0;
}
});
futures[0] = c1;
//乘10操作
CompletableFuture c2 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("乘10任务开始。");
return num *= 10;
} catch (InterruptedException e) {
e.printStackTrace();
return 0;
}
});
futures[1] = c2;
//减10操作
CompletableFuture c3 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("减10任务开始。");
return num -= 10;
} catch (InterruptedException e) {
e.printStackTrace();
return 0;
}
});
futures[2] = c3;
//除10操作
CompletableFuture c4 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("除10任务开始。");
return num /= 10;
} catch (InterruptedException e) {
e.printStackTrace();
return 0;
}
});
futures[3] = c4;
CompletableFuture