java.util.concurrent
本文最后更新于:2 小时前
进程和线程
进程和线程
进程:程序的集合,CPU调度资源的基本单位
线程:一个进程至少包含一个线程,资源分配的基本单位
Java 默认有两个线程:main 和 GC
Java 真的可以开启线程吗?不可以,只能调用底层C++,public native void start()。java 无法直接操作硬件
并发和并行
并发(多线程操作同一个资源)
- CPU一核,模拟多条线程,快速交替
并行
- 多个线程同时执行
并发编程的本质:充分利用 CPU 的资源
线程的状态
进入源码,源码中枚举出了六种类型
public enum State {
// 新生
NEW,
// 运行
RUNNABLE,
// 阻塞
BLOCKED,
// 等待
WAITING,
// 超市等待
TIMED_WAITING,
// 终止
TERMINATED;
}
wait/sleep 区别
- 来自不同的类 wait:Object, sleep:Thread。
- 关于锁的释放:wait:会释放锁,sleep:不释放锁。
- 使用的范围不同:wait:必须在同步代码块中,sleep可以在任何地方使用。
- 捕获异常:wait:不需要,sleep:必须捕获异常。
- 唤醒:wait需要唤醒,sleep不需要
Lock锁
传统 synchronized
package xyz.qiuqian.juc;
// 卖票demo
/**
* 真正的多线程呢开发,线程就是一个单独的资源类,没有任何附属操作
* 包含:属性,方法
*/
public class SaleTicketDemo01 {
public static void main(String[] args) {
// 并发:多线程操作同一个资源类
Ticket ticket = new Ticket();
// 函数式接口
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 < 60; i++) {
// ticket.sale();
// }
}, "C").start();
}
}
// 资源类 OOP面向对象编程
class Ticket {
private int ticketNum = 50;
// synchronized 本质就是排队
public synchronized void sale() {
if ( ticketNum > 0 ) {
// ticketNum--;
System.out.println(Thread.currentThread().getName() + "卖出了第" + ticketNum-- + "张票,剩下" + ticketNum + "张");
}
}
}
Lock接口
公平锁:FIFO
非公平锁:可以插队,默认是非公平锁
package xyz.qiuqian.juc;
// 卖票demo
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 真正的多线程呢开发,线程就是一个单独的资源类,没有任何附属操作
* 包含:属性,方法
*/
public class SaleTicketDemo02 {
public static void main(String[] args) {
Ticket2 ticket = new Ticket2();
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 Ticket2 {
private int ticketNum = 30;
Lock lock = new ReentrantLock();
public void sale() {
lock.lock();
try {
// 业务代码在try里面
if ( ticketNum > 0 ) {
System.out.println(Thread.currentThread().getName() + "卖出了第" + ticketNum-- + "张票,剩下" + ticketNum + "张");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
Synchronized 和 Lock 区别
- Synchronized 是内置的 Java 关键字,Lock 是 Java 类
- Synchronized 无法判断获取锁的状态,Lock 可以判断是否获取到了锁
- Synchronized 会自动释放锁,Lock 锁必须要手动释放锁,否则造成死锁
- Synchronized 线程1(获得锁,阻塞),线程2(一直等待)。Lock 锁不一定一直等待
- Synchronized 是可重入锁,不可中断的,非公平。Lock 可重入,可以判断锁,可以自行设置
- Synchronized 适合锁少量的代码同步问题,Lock适合锁大量的同步代码
生产者和消费者问题
Synchronized 版
package xyz.qiuqian.juc.demo01.pc;
/**
* 线程之间的通信问题,生产者消费者问题 等待唤醒,通知唤醒
* 线程交替执行 A, B 操作同一个变量 num = 0
* A: num + 1
* B: num - 1
*/
public class Test {
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.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").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);
// 通知其他线程
this.notifyAll();
}
}
注意!! 防止虚假唤醒:if -> while
package xyz.qiuqian.juc.demo01.pc;
/**
* 线程之间的通信问题,生产者消费者问题 等待唤醒,通知唤醒
* 线程交替执行 A, B 操作同一个变量 num = 0
* A: num + 1
* B: num - 1
*/
public class Test {
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.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
new Thread(()-> {
for (int i = 0; i < 10; i++) {
try {
data.increment();
} 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 {
while ( num != 0 ) {
// 等待
this.wait();
}
num++;
System.out.println(Thread.currentThread().getName() + "=>" + num);
// 通知其他线程
this.notifyAll();
}
// -1
public synchronized void decrement() throws InterruptedException {
while ( num == 0 ) {
// 等待
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName() + "=>" + num);
// 通知其他线程
this.notifyAll();
}
}
在 Java 官方文档中是这样写的
线程也可以唤醒,而不会被通知,中断或超时,即所谓的虚假唤醒。虽然这在实践中很少会发生,但应用程序必须通过测试应该使该线程被唤醒的条件来防范,并且如果条件不满足则继续等待。换句话说,等待应该总是出现在循环中
JUC 版
package xyz.qiuqian.juc.pc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 线程之间的通信问题,生产者消费者问题 等待唤醒,通知唤醒
* 线程交替执行 A, B 操作同一个变量 num = 0
* A: num + 1
* B: num - 1
*/
public class JUC {
public static void main(String[] args) {
Data2 data = new Data2();
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.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
new Thread(()-> {
for (int i = 0; i < 10; i++) {
try {
data.increment();
} 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 Data2 {
private int num = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
// +1
public void increment() throws InterruptedException {
try {
lock.lock();
while ( num != 0 ) {
// 等待
condition.await();
}
num++;
System.out.println(Thread.currentThread().getName() + "=>" + num);
// 通知其他线程
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
// -1
public void decrement() throws InterruptedException {
try {
lock.lock();
while ( num == 0 ) {
// 等待
condition.await();
}
num--;
System.out.println(Thread.currentThread().getName() + "=>" + num);
// 通知其他线程
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
Condition 精准通知和唤醒线程
Condition:同步监视器,以便更好控制 lock
package xyz.qiuqian.juc.pc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Condition_ {
public static void main(String[] args) {
Data3 data = new Data3();
new Thread(()-> {
for (int i = 0; i < 10; i++) {
data.printA();
}
}, "A").start();
new Thread(()-> {
for (int i = 0; i < 10; i++) {
data.printB();
}
}, "B").start();
new Thread(()-> {
for (int i = 0; i < 10; i++) {
data.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;
public void printA() {
lock.lock();
try {
// 业务, 判断->执行->通知
while ( num != 1) {
condition1.await();
}
System.out.println(Thread.currentThread().getName() + " => AAAAA");
// 唤醒指定B
num = 2;
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void printB() {
lock.lock();
try {
while ( num != 2 ) {
// 等待
condition2.await();
}
System.out.println(Thread.currentThread().getName() + " => BBBBB");
num = 3;
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC() {
lock.lock();
try {
while ( num != 3 ) {
condition3.await();
}
System.out.println(Thread.currentThread().getName() + " => CCCCC");
num = 1;
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
8锁现象
/**
* 关于锁的8个问题
* 1. 标准情况下,两个线程是先发短信还是先打电话?
* 2. 发短信的方法延迟4秒,两个线程是先发短信还是先打电话?
* synchronized 锁的对象是方法的调用者,两个方法用同一个锁,谁先拿到锁谁先执行!
* 3. 增加了一个普通方法后,先打印发短信还是hello?
* 普通方法hello,没有锁,不是同步方法,不受锁的影响!
* 4. 两个对象,两个同步方法,先执行发短信还是打电话?
* 两个对象,两个调用者,拿到的是两个不同的锁,按照时间顺序执行!
* 5. 增加两个静态的同步方法,只有一个对象,两个线程是先发短信还是先打电话?
* static静态方法,类一加载就有了,锁的是Class对象!两个方法都被static修饰,拿到的都是同一个锁。可以再加一个Phone对象测试
* 6. 增加两个静态的同步方法,两对象,两个线程是先发短信还是先打电话?
* static静态方法,类一加载就有了,锁的是Class对象!两个方法都被static修饰,拿到的都是同一个锁。和5类似
* 7. 一个静态同步方法,一个普通同步方法,只有一个对象,两个线程是先发短信还是先打电话?
* 一个锁的是class模版,一个锁的是调用者,是两个不同的锁
* 8. 一个静态同步方法,一个普通同步方法,两个个对象,两个线程是先发短信还是先打电话?
* 和6类似,是两个不同的锁
*/
具体见代码
小结
new this,具体的一个对象
static class,唯一的一个模版
集合类不安全
List 不安全
package xyz.qiuqian.unsafe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
// java.util.ConcurrentModificationException 并发修改异常
public class ListTest {
public static void main(String[] args) {
// 并发下 ArrayList 不安全
/**
* 解决方案
* 1. vector 经过源码查看
*
*
*/
List<String> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
new Thread(()-> {
list.add(UUID.randomUUID().toString().substring(0, 5));
System.out.println(list);
}, String.valueOf(i)).start();
}
}
}
解决方案:
vector 经过查看源码,
)
),vector(1.0) 比 list(1.2) 先出来,但是vector有synchronized修饰,list却没有
集合类转为安全
CopyOnWrite
那么问题来了, CopyOnWriteArrayList 比 Vector 好在哪里?
还是看源码
vector 的源码在上面可以看
下面是CopyOnWriteArrayList 的add源码
可以看到,vector 使用的 synchronized ,效率会比使用 lock 的 CopyOnWrite 低
没事多看看源码,看看底层怎么实现的,就能知道在什么时候选择什么方式会有更高的效率~
Set 不安全
package xyz.qiuqian.unsafe;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* 同理可得 java.util.ConcurrentModificationException 并发修改异常
*
*/
public class SetTest {
public static void main(String[] args) {
// 出错
// Set<String> set = new HashSet<>();
// 解决方案1, 集合类转为安全
// Set<String> set = Collections.synchronizedSet(new HashSet<>());
// 解决方案2, CopyOnWrite
Set<String> set = new CopyOnWriteArraySet<>();
for (int i = 0; i < 30; i++) {
new Thread(()-> {
set.add(UUID.randomUUID().toString().substring(0, 5));
System.out.println(set);
}, String.valueOf(i)).start();
}
}
}
顺带:HashSet的底层是什么?看源码看源码
HashSet 的 add 方法
set 本质就是 map, key 是无法重复的
PRESENT 是一个常量,不会变的值
HashMap 不安全
TODO
package xyz.qiuqian.unsafe;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* java.util.ConcurrentModificationException
*/
public class MapTest {
public static void main(String[] args) {
// map 是这样用的吗? 不是
// 默认等价与什么? new HashMap<>(16, 0.75)
//Map<String, String> map = new HashMap<>();
// 加载因子,初始化容量
// 解决方案
Map<String, String> map = new ConcurrentHashMap<>();
for (int i = 0; i < 300; i++) {
new Thread(()-> {
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 5));
System.out.println(map);
}, String.valueOf(i)).start();
}
}
}
Callable
官方文档中的描述
Callable 接口类似于 Runnable,因为他们都是为其实例可能由另一个线程执行的类设计的,然而, Runnable 不返回结果,也不能抛出被检查的异常。
改 Executors 类包含的实用方法,从其他普通形式转换为 Callable类。
总结:
- 可以有返回值
- 可以抛出异常
- 方法不同,run() / call()
package xyz.qiuqian.callable;
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 {
new Thread().start(); // 怎么启动callable
MyThread myThread = new MyThread();
FutureTask futureTask = new FutureTask(myThread);
new Thread(futureTask, "A").start();
new Thread(futureTask, "B").start(); // 结果会被缓存,提高效率
// 获取callable的返回结果
// 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
- CyclicBarrier
- Semaphore
CountDownLatch
允许一个或多个线程等待直到在其他线程中执行的一组操作完成的同步辅助
说人话:减法计数器
package xyz.qiuqian.add;
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 < 6; i++) {
new Thread(()-> {
System.out.println(Thread.currentThread().getName() + "run 了");
countDownLatch.countDown(); // -1
}, String.valueOf(i)).start();
}
// 里面的顺序不关系,但是只要里面的东西都完了再执行下面的内容
countDownLatch.await(); // 等待计数器归零,然后向下执行
System.out.println("你给我回来!");
}
}
原理:
countDownLatch.countDown(); // -1
countDownLatch.await(); // 等待计数器归零,然后向下执行
每次有线程调用 countDown() ,数量-1。假设计数器变为0, countDownLatch.await() 被唤醒,继续执行
CyclicBarrier
允许一组线程全部等待彼此到达共同屏障点的同步辅助。循环阻塞在涉及固定大小的线程方法中很有用,这些线程必须偶尔等待彼此。屏障被称为循环,因为它可以在等待的线程被释放之后重新使用。
说人话:加法计数器
package xyz.qiuqian.add;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String[] args) {
// 集齐七颗龙珠召唤神龙
// 召唤龙珠的线程
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, ()-> {
System.out.println("done!");
});
for (int i = 1; i <= 7; i++) {
// Lambda 能操作到 i 吗 ? 不能 需要使用 final 修饰
final int temp = i;
new Thread(()-> {
System.out.println(Thread.currentThread().getName() + "收集了 " + temp + " 个龙珠");
// 这个辅助类是通过await来记数的,await之后本次线程会被阻塞,直到done后才执行下面的
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
Semaphore
一个计数信号量,在概念上,信号量维护一组许可证。如果有必要,每个 acquire() 都会阻塞,直到许可证可用,然后才能使用它。每个 release() 添加许可,潜在地释放阻塞获取方。但是,没有使用实际的许可证对象;Semaphore 只保留可用数量的计数,并相应地执行。
package xyz.qiuqian.add;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
// 停车位 3个停车位,6个车
public class SemaphoreDemo {
public static void main(String[] args) {
// 参数为线程数量
// 限流时也会用
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <= 6; i++) {
new Thread(()-> {
// acquire() 得到
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();
}
// release() 释放
}, String.valueOf(i)).start();
}
}
}
原理:
- acquire():获得,假设已满,等待被释放为止
- release():释放,会将当前的信号量释放+1,然后唤醒等待的线程
作用:
- 多个共享资源互斥时使用
- 并发限流,控制最大的线程数
读写锁
ReadWriteLock
读可以被多个线程同时读,写的时候只能有一个线程写
package xyz.qiuqian.rw;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 读-读 v
* 读-写 x
* 写-写 x
*/
public class ReadWriteLockDemo {
public static void main(String[] args) {
// MyCache myCache = new MyCache();
MyCacheLock myCache = new MyCacheLock();
// 写入
for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(() -> {
myCache.put(temp + "", temp + "");
}, String.valueOf(i)).start();
}
// 读取
for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(() -> {
myCache.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() + "写入" + key);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "写入成功");
}
// 取,读
public Object get(String key) {
System.out.println(Thread.currentThread().getName() + "读取" + key);
System.out.println(Thread.currentThread().getName() + "读取成功");
return map.get(key);
}
}
/**
* 自定义缓存
* 加锁
*/
class MyCacheLock {
private volatile Map<String, Object> map = new HashMap<>();
// 读写锁,更加细粒度的控制
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
// 存,写,写入的时候只希望同时只有一个线程往里面写
public void put(String key, Object value) {
readWriteLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "写入" + key);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "写入成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}
// 取,读,所有线程都可以读
public void get(String key) {
readWriteLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "读取" + key);
System.out.println(Thread.currentThread().getName() + "读取成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
}
}
阻塞队列 ArrayBlockingQueue
使用场景:多线程并发处理,线程池
四组API
- 抛出异常
- 不会抛出异常
- 阻塞等待
- 超时等待
方式 | 抛出异常 | 不抛出异常,有返回值 | 阻塞等待 | 超时等待 |
---|---|---|---|---|
添加 | add() | offer() | put() | offer(,,) |
移除 | remove() | poll() | take() | poll(,) |
判断队列首部 | element() | peek() | - | - |
package xyz.qiuqian.bq;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) throws InterruptedException {
test4();
}
/**
* 抛出异常
*/
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"));
// 检测队首元素值
System.out.println(blockingQueue.element());
System.out.println("==================");
//java.lang.IllegalStateException: Queue full
// System.out.println(blockingQueue.add("d"));
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.element());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//java.util.NoSuchElementException
// System.out.println(blockingQueue.remove());
}
/**
* 不抛出异常
*/
public static void test2() {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
// 检测队首元素
System.out.println(blockingQueue.peek());
System.out.println("==================");
// 不抛出异常,返回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());
}
/**
* 等待阻塞,一直阻塞
*/
public static void test3() throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
System.out.println("==================");
// 队列没有位置,一直等待
// blockingQueue.put("d");
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
// 没有这个元素,一直阻塞等待
System.out.println(blockingQueue.take());
}
/**
* 等待阻塞,等待超时
*/
public static void test4() throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.offer("a");
blockingQueue.offer("b");
blockingQueue.offer("c");
// 等待超出两秒退出阻塞
blockingQueue.offer("d", 2, TimeUnit.SECONDS);
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
// 等待超出两秒退出阻塞
System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
}
}
同步队列 SynchronousQueue
没有容量:进去一个元素必须等待取出后才能再往里面放一个元素
package xyz.qiuqian.bq;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
/**
* 同步队列
* SynchronousQueue 不存储元素,put 了一个元素,必须从里面先 take 出,否则不能再 put 值进去
*/
public class SynchronousQueueDemo {
public static void main(String[] args) {
// 同步队列
SynchronousQueue<String> synchronousQueue = new SynchronousQueue();
new Thread(() -> {
try {
// 写入一个元素后必须等待拿出后才能继续写入
System.out.println(Thread.currentThread().getName() + " put 1 ");
synchronousQueue.put("1");
System.out.println(Thread.currentThread().getName() + " put 2 ");
synchronousQueue.put("2");
System.out.println(Thread.currentThread().getName() + " put 3 ");
synchronousQueue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "T1").start();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + " => " + synchronousQueue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + " => " + synchronousQueue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + " => " + synchronousQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "T2").start();
}
}
线程池
线程池:三大方法,七大参数,四种拒绝策略
程序运行的本质就是占用系统资源
线程池、连接池、内存池、对象池
池化技术:事先准备资源,当需要使用时到池中取,用完后放回。
线程池的好处:
- 降低资源消耗
- 提高响应速度,没有创建和销毁这类消耗资源的操作
- 方便管理
线程复用,可以控制最大并发数,管理线程
三大方法
package xyz.qiuqian.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// Executors 工具类,三大方法
public class Demo01 {
public static void main(String[] args) {
// ExecutorService threadPool = Executors.newSingleThreadExecutor();// 单个线程
ExecutorService threadPool = Executors.newFixedThreadPool(5);// 创建一个固定的线程池的大小
// ExecutorService threadPool = Executors.newCachedThreadPool();// 可伸缩的
try {
for (int i = 0; i < 100; i++) {
// new Thread().start(); // 传统方式
// 使用线程池创建线程
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " => ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 线程池用完,程序结束,关闭线程池
threadPool.shutdown();
}
}
}
七大参数
ExecutorService threadPool = Executors.newSingleThreadExecutor();// 单个线程
ExecutorService threadPool = Executors.newFixedThreadPool(5);// 创建一个固定的线程池的大小
ExecutorService threadPool = Executors.newCachedThreadPool();// 可伸缩的
先看下三种方法的源码时怎么实现的
这里面可以看到,三种方式都是使用 ThreadPoolExecutor 创建线程池,但是其中参数不同,再次查看 ThreadPoolExecutor 的源码
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.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
结合这七个参数回头分析三个创建线程的源码,newCachedThreadPool 的前两个参数为 0, Integer.MAX_VALUE,约等于21亿。。。如果没有这么多线程的话,很容易就发生内存溢出了。也难怪阿里巴巴Java开发手册中线程池不允许使用 Executors 去创建,并且级别是【强制】。
手动创建一个线程池
四种拒绝策略
AbortPolicy() // 如果队列满,还有需要处理的东西进来,不处理且抛出异常
CallerRunsPolicy() // 从哪来回哪去,如果是从main线程来,则有main线程处理
DiscardOldestPolicy() // 队列满,尝试去和最早的竞争,失败=>无,成功=>执行。无异常抛出
DiscardPolicy() // 队列满,丢掉任务,不会抛出异常
package xyz.qiuqian.pool;
import java.util.concurrent.*;
// Executors 工具类,三大方法
public class Demo01 {
public static void main(String[] args) {
// 自定义线程池
/**
* 银行业务窗口
* 两个开放,三个不开放
*/
ExecutorService threadPool = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy()
);
try {
// 最大承载 = 队列 + max值
// 超出最大承载被拒绝策略拒绝,且抛出异常 java.util.concurrent.RejectedExecutionException
for (int i = 1; i <= 100; i++) {
// new Thread().start(); // 传统方式
// 使用线程池创建线程
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " => ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 线程池用完,程序结束,关闭线程池
threadPool.shutdown();
}
}
}
CPU 密集 / IO 密集
池的最大大小/最大线程如何定义?
CPU 密集型:几核 CPU 就定义几,保证CPU的效率最高。需要通过代码获取!
System.out.println(Runtime.getRuntime().availableProcessors());
IO 密集型:假设有15个大型任务,IO很占用资源,通常处理方式是至少留15个线程处理IO。
判断程序中十分消耗 IO 的线程。一般设置两倍于 IO 线程。
四大函数式接口
lambda表达式、链式编程、函数式接口、Stream流式计算
函数式接口:只有一个方法的接口,比如 Runnable 接口,ForEach(消费者类型的函数式接口)。
作用:可以简化编程模型,在新版本的框架底层大量应用
Function 函数型
函数型接口
传入参数 T,返回 R
package xyz.qiuqian.function;
import java.util.function.Function;
/**
* Function 函数型接口
*
* 特性:
* 一个输入参数,一个输出
* 只要是函数式接口,就可以用 lambda 表达式简化
*/
public class Demo01 {
public static void main(String[] args) {
// 匿名内部类
// 工具类,输出输入的值
// Function function = new Function<String, String>() {
// @Override
// public String apply(String o) {
// return o;
// }
// };
// Function<String, String> function = (str) -> {
// return str;
// };
Function<String, String> function = str -> {return str;};
System.out.println(function.apply("123"));
}
}
Predicate 断定型
断定型接口,有一个输入参数,返回值只能是bool值
package xyz.qiuqian.function;
import java.util.function.Predicate;
/**
* 断定型接口,有一个输入参数,返回值只能是bool值
*
*/
public class Demo02 {
public static void main(String[] args) {
// 判断字符串是否为空
Predicate<String> predicate = new Predicate<String>() {
@Override
public boolean test(String str) {
return str.isEmpty();
}
};
Predicate<String> predicate1 = str -> {return str.isEmpty();};
System.out.println(predicate.test("123"));
System.out.println(predicate1.test(""));
}
}
Consumer 消费型
只有输入参数,无返回值
package xyz.qiuqian.function;
import java.util.function.Consumer;
/**
*
*/
public class Demo03 {
public static void main(String[] args) {
Consumer<String> consumer = new Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
};
Consumer<String> consumer1 = str -> {
System.out.println(str);
};
consumer.accept("qiuqian");
consumer1.accept("aowu");
}
}
Supplier 供给型
没有参数,只有返回值
package xyz.qiuqian.function;
import java.util.function.Supplier;
/**
* Supplier 供给型接口
*/
public class Demo04 {
public static void main(String[] args) {
Supplier supplier = new Supplier<Integer>() {
@Override
public Integer get() {
return 1024;
}
};
Supplier supplier1 = () -> {return 1024;};
System.out.println(supplier.get());
System.out.println(supplier1.get());
}
}
Stream 流计算
大数据:存储 + 计算
存储:集合,MySQL
计算:都应该交给流操作
package xyz.qiuqian.stream;
import java.util.Arrays;
import java.util.List;
/**
* 1. id 为偶数
* 2. 年龄大于23岁
* 3. 用户名转化为大写
* 4. 倒序用户名
* 5. 只输出一个
*/
public class Test {
public static void main(String[] args) {
User u1 = new User(1, "a", 21);
User u2 = new User(2, "b", 22);
User u3 = new User(3, "c", 23);
User u4 = new User(4, "d", 24);
User u5 = new User(5, "e", 25);
List<User> list = Arrays.asList(u1, u2, u3, u4, u5);
list.stream()
.filter(user -> { return user.getId() % 2 == 0; })
.filter(user -> { return user.getAge() > 23; })
.map(user -> { return user.getName().toUpperCase(); })
.sorted((user1, user2) -> { return user2.compareTo(user1); })
.limit(1)
.forEach(System.out::println);
}
}
异步回调
对将来某个时间结果进行建模
package xyz.qiuqian.future;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* 异步调用: Ajax
* 异步执行
* 成功回调
* 失败回调
*/
public class Demo01 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 没有返回值的 runAsync 异步回调
// CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
// try {
// TimeUnit.SECONDS.sleep(2);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName() + "runAsync => Void");
// });
//
// System.out.println("111");
//
// completableFuture.get(); // 获取阻塞执行结果
// 有返回值的 supplyAsync 异步回调
// Ajax 成功和失败的回调
// 失败: 返回错误信息
CompletableFuture<Integer> uCompletableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + " => supplyAsync=>Integer");
int i = 10 / 0;
return 200;
});
uCompletableFuture.whenComplete((t, u) -> {
System.out.println("t => " + t);
System.out.println("u => " + u);
}).exceptionally((e) -> {
System.out.println(e.getMessage());
return 500; // 可以获取到错误的返回结果
}).get();
}
}
JMM
Volatile 是 Java 虚拟机提供的轻量级的同步机制
- 保证可见性
- 不保证原子性
- 禁止指令重排
JMM:Java Memory Modal,Java 内存模型,不存在的东西,是一个概念约定。
关于 JMM 的同步约定
- 线程解锁前,必须把共享变量立刻刷会主存
- 线程加锁前,必须读取主存中的最新值到工作内存中
- 加锁和解锁是同一把锁
线程、工作内存、主内存
Volatile
保证可见性
package xyz.qiuqian.volatiledemo;
import java.util.concurrent.TimeUnit;
public class Demo01 {
// 不加 volatile 程序会死循环
// 加 volatile 可以保证可见性
private volatile static int 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在执行的时候不能被打扰,也不能被分割。要么同时成功,要么同时失败。
package xyz.qiuqian.volatiledemo;
// volatile 不保证原子性
public class Demo02 {
private volatile static int num = 0;
public static void add() {
num++;
}
public static void main(String[] args) {
// 此时理论上结果为20000
for (int i = 1; i <= 20 ; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
add();
}
}).start();
}
while ( Thread.activeCount() > 2 ) { // main GC
Thread.yield(); // 礼让
}
System.out.println(Thread.currentThread().getName() + " " + num);
}
}
如果不加 lock 和 synchronized,怎么保证原子性?
private volatile static AtomicInteger num = new AtomicInteger();
package xyz.qiuqian.volatiledemo;
import java.util.concurrent.atomic.AtomicInteger;
// volatile 不保证原子性
public class Demo02 {
// 原子类Integer
private volatile static AtomicInteger num = new AtomicInteger();
public static void add() {
/**
* 这个函数在字节码中可以查看到一共分为三步
* 1 获取这个值
* 2 +1
* 3 写回这个值
*/
// num++; // 不是一个原子性操作
num.getAndIncrement(); // 使用的是底层 CAS
}
public static void main(String[] args) {
// 此时理论上结果为20000
for (int i = 1; i <= 20 ; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
add();
}
}).start();
}
while ( Thread.activeCount() > 2 ) { // main GC
Thread.yield(); // 礼让
}
System.out.println(Thread.currentThread().getName() + " " + num);
}
}
这些类的底层都直接和操作系统挂钩。是直接在内存中修改值的。 Unsafe 类是一个很特殊的存在。
禁止指令重排
什么是指令重排:计算机并不是按照你写的程序的顺序执行的。
源代码 => 编译器优化源代码 => 指令并行也可能会重排 => 内存系统也会重拍 =>执行
计算机在进行指令重排时,考虑数据之间的依赖性
int x = 1; // 1
int y = 2; // 2
x = x + 5; // 3
y = x * x; // 4
/**
* 期望程序执行的顺序:1 2 3 4
* 但执行的时候可能变成 2 1 3 4 / 1 3 2 4
* 但不可能是 4 1 2 3
*/
可能造成影响的结果: 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 |
指令重排导致的异常结果:x = 2, y = 1
指令重排虽然出现的概率非常小,但是理论上它还是会出现,墨菲定律,需要禁止重排
volatile 可以避免指令重排:内存屏障,CPU指令。作用:
- 保证特定的操作的执行顺序
- 可以保证某些变量的内存可见性(利用这些特性就可以保证 volatile 实现了可见性)
单例模式
什么玩意儿,太深入了没听懂,有空回头再听听…具体看代码吧
CAS
比较当前工作内存中的值和主内存中的值,如果这个值是期望的,则执行操作。如果不是,while,自旋锁一直循环。
缺点:
- 自旋锁循环耗时
- 一次性只能保证一个共享变量的原子性
- 会存在ABA问题
package xyz.qiuqian.cas;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;
/**
* CAS: compare and set 比较并交换
*/
public class CASDemo {
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(2022);
/**
* public final boolean compareAndSet(int expect, int update) {
* return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
* }
*/
// 如果拿到了期望值,就更新,否则不更新
// CAS 是 CPU 的并发原语
atomicInteger.compareAndSet(2022, 2023);
System.out.println(atomicInteger.get());
/**
* public final int getAndIncrement() {
* return unsafe.getAndAddInt(this, valueOffset, 1);
* }
* unsafe: Java 无法操纵内存,但可以调用cpp操作内存
* 相当于Java的后门,通过这个类操作内存
*
*/
/**
* public final int getAndAddInt(Object var1, long var2, int var4) {
* int var5;
* do {
* var5 = this.getIntVolatile(var1, var2);
* } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
*
* return var5;
* }
*
* 自旋锁
*/
atomicInteger.getAndIncrement();// ++
// 修改失败,返回false
System.out.println(atomicInteger.compareAndSet(2022, 2023));
}
}
原子引用
解决ABA问题,和乐观锁原理相同
带版本号的原子操作
package xyz.qiuqian.cas;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;
public class AtomicStampedReferenceDemo {
public static void main(String[] args) {
// 如果范性是包装类,注意对象的引用问题
AtomicStampedReference<Integer> integerAtomicStampedReference = new AtomicStampedReference<>(1, 1);
new Thread(() -> {
int stamp = integerAtomicStampedReference.getStamp();// 获取版本号
System.out.println("A1 => " + stamp);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 乐观锁每次执行完成后会把 version + 1
System.out.println(integerAtomicStampedReference.compareAndSet(1,
2,
integerAtomicStampedReference.getStamp(),
integerAtomicStampedReference.getStamp() + 1
));
System.out.println("A2 => " + integerAtomicStampedReference.getStamp());
System.out.println(integerAtomicStampedReference.compareAndSet(2,
1,
integerAtomicStampedReference.getStamp(),
integerAtomicStampedReference.getStamp() + 1
));
System.out.println("A3 => " + integerAtomicStampedReference.getStamp());
}, "A").start();
// 和乐观锁原理相同
new Thread(() -> {
int stamp = integerAtomicStampedReference.getStamp();// 获取版本号
System.out.println("B1 => " + stamp);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(integerAtomicStampedReference.compareAndSet(1, 6, stamp, stamp + 1));
System.out.println("B1 => " + integerAtomicStampedReference.getStamp());
}, "B").start();
}
}
锁
公平锁,非公平锁
公平:FIFO,不允许插队
非公平:可以插队
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
可重入锁
也叫做递归锁
拿到了外面的锁,也就可以自动拿到里面的锁
package xyz.qiuqian.lock;
// Synchronized
public class Demo01 {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(() -> {
phone.sms();
}, "A").start();
new Thread(() -> {
phone.sms();
}, "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");
}
}
package xyz.qiuqian.lock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo02 {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(() -> {
phone.sms();
}, "A").start();
new Thread(() -> {
phone.sms();
}, "B").start();
}
}
class Phone2 {
Lock lock = new ReentrantLock(); // lock 锁必须配对
public void sms() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " sms");
call();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void call() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " call");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
自旋锁
自定义自旋锁
package xyz.qiuqian.lock;
import java.util.concurrent.TimeUnit;
public class SpinLockTest {
public static void main(String[] args) throws InterruptedException {
// 底层使用的自旋锁 cas
SpinlockDemo spinlockDemo = new SpinlockDemo();
new Thread(() -> {
spinlockDemo.myLock();
try {
TimeUnit.SECONDS.sleep(3);
} catch (Exception e) {
e.printStackTrace();
} finally {
spinlockDemo.myUnlock();
}
}, "T1").start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
spinlockDemo.myLock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
spinlockDemo.myUnlock();
}
}, "T2").start();
}
}
Test
package xyz.qiuqian.lock;
import java.util.concurrent.atomic.AtomicReference;
/**
* 自旋锁
*/
public class SpinlockDemo {
AtomicReference<Thread> threadAtomicReference = new AtomicReference<>();
// 加锁
public void myLock() {
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName() + " ===> myLock");
// 自旋锁
while(!threadAtomicReference.compareAndSet(null, thread)) {
}
}
// 解锁
public void myUnlock() {
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName() + " ===> myUnlock");
threadAtomicReference.compareAndSet(thread, null);
}
}
死锁
怎么排除死锁
死锁四个必要条件:
- 互斥
- 持有并等待
- 不可剥夺
- 成环
package xyz.qiuqian.lock;
import sun.awt.windows.ThemeReader;
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), "T2").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);
}
}
}
}
解决死锁:
jdk bin目录下
- 使用 jps 定位进程号: jps -l
- 使用 jstack 查看进程信息: jstack 进程号
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!