JUC 多线程编程
1,前提
关于线程还是进程
一个进程(程序)有多个进程
关于是并发还是并行
-
并发(多线程操作同一个资源)
CPU 一核 ,模拟出来多条线程,天下武功,唯快不破,快速交替
-
并行(多个人一起行走)
CPU 多核 ,多个线程可以同时执行; 线程池
线程有几个状态
// 新生
NEW,
// 运行
RUNNABLE,
// 阻塞
BLOCKED,
// 等待,死死地等
WAITING,
// 超时等待
TIMED_WAITING,
// 终止
TERMINATED;
wait/sleep 区别
1、来自不同的类
wait => Object
sleep => Thread
2、关于锁的释放
wait 会释放锁,sleep 睡觉了,抱着锁睡觉,不会释放!
3、使用的范围是不同的
wait 必须在同步代码块中.
sleep 可以再任何地方睡
4、是否需要捕获异常
wait 不需要捕获异常
sleep 必须要捕获异常
2,同步机制
Synchronized 和 Lock 区别
1、Synchronized 内置的Java关键字, Lock 是一个Java类
2、Synchronized 无法判断获取锁的状态,Lock 可以判断是否获取到了锁
3、Synchronized 会自动释放锁,lock 必须要手动释放锁!如果不释放锁,死锁
4、Synchronized 线程 1(获得锁,阻塞)、线程2(等待,傻傻的等);Lock锁就不一定会等待 下去;
5、Synchronized 可重入锁,不可以中断的,非公平;Lock ,可重入锁,可以 判断锁,非公平 (可以自己设置);
6、Synchronized 适合锁少量的代码同步问题,Lock 适合锁大量的同步代码!
3,Lock锁
传统 Synchronized
public class SaleTicketDemo {
public static void main(String[] args) {
// 并发: 多线程操作同一个资源类
Ticket ticket = new Ticket();
//@FunctionalInterface 函数式接口 jdk1.8 lambda表达式
new Thread(()->{
for (int i = 0; i < 60; i++) {
ticket.sale();
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 60; i++) {
ticket.sale();
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 60; i++) {
ticket.sale();
}
},"C").start();
}
}
//资源类 OOP
class Ticket{
//属性 方法
private int number = 50;
//synchronized 队列和锁
public synchronized void sale(){
if(number>0){
System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票 , 剩余: "+number);
}
}
//锁 对象
}
Lock 接口
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d3oiagfU-1607392386163)(C:\Users\胡歌\AppData\Roaming\Typora\typora-user-images\image-20201203164054306.png)]
公平锁:十分公平:可以先来后到
非公平锁:十分不公平:可以插队 (默认)
//资源类 OOP
class Ticket2{
//属性 方法
private int number = 50;
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 是一个Java类
2、Synchronized 无法判断获取锁的状态,Lock 可以判断是否获取到了锁
3、Synchronized 会自动释放锁,lock 必须要手动释放锁!如果不释放锁,死锁
4、Synchronized 线程 1(获得锁,阻塞)、线程2(等待,傻傻的等);Lock锁就不一定会等待 下去;
5、Synchronized 可重入锁,不可以中断的,非公平;Lock ,可重入锁,可以 判断锁,非公平 (可以自己设置);
6、Synchronized 适合锁少量的代码同步问题,Lock 适合锁大量的同步代码!
4,生产者和消费者问题
生产者和消费者问题 Synchronized 版
public class Buffer {
private int num = 0;
public synchronized void add() throws InterruptedException {
while (num!=0){
//等待
this.wait();
}
num++;
System.out.println(Thread.currentThread().getName()+"---"+num);
//通知其他线程
this.notifyAll();
}
public synchronized void sub() throws InterruptedException {
/**
* 就是用if判断的话,唤醒后线程会从wait之后的代码开始运行,但是不会重新判断if条件,
* 直接继续运行if代码块之后的代码,而如果使用while的话,
* 也会从wait之后的代码运行,但是唤醒后会重新判断循环条件,
* 如果不成立再执行while代码块之后的代码块,成立的话继续wait
*/
// if(num==0){
// //等待
// this.wait();
// }
//用 while 防止虚假唤醒的情况
while (num==0){
//等待
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName()+"---"+num);
//通知其他线程
this.notifyAll();
}
}
if存在问题 虚假唤醒 解决办法改成while
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EANkw0SK-1607392386176)(C:\Users\胡歌\AppData\Roaming\Typora\typora-user-images\image-20201203165200077.png)]
JUC版的生产者和消费者问题
public class Buffer2 {
private int num = 0;
final Lock lock = new ReentrantLock();
final Condition condition = lock.newCondition();
public void add() throws InterruptedException {
lock.lock();
try {
while (num!=0){
//等待
condition.await();
}
num++;
System.out.println(Thread.currentThread().getName()+"---"+num);
//通知其他线程
condition.signalAll();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void sub() throws InterruptedException {
lock.lock();
try {
while (num==0){
//等待
condition.await();
}
num--;
System.out.println(Thread.currentThread().getName()+"---"+num);
//通知其他线程
condition.signalAll();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
Condition 精准的通知和唤醒线程
public class Buffer3 {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data.printA();
}
}).start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data.printB();
}
}).start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data.printC();
}
}).start();
}
}
class Data{
private int num = 1;
Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
public void printA(){
lock.lock();
try {
while (num!=1){
condition1.await();
}
num=2;
System.out.println(Thread.currentThread().getName()+"--AAA");
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB(){
lock.lock();
try {
while (num!=2){
condition2.await();
}
num=3;
System.out.println(Thread.currentThread().getName()+"--BBB");
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC(){
lock.lock();
try {
while (num!=3){
condition3.await();
}
num=1;
System.out.println(Thread.currentThread().getName()+"--CCC");
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
5,集合类不安全
List 不安全
public class TestList {
public static void main(String[] args) {
//java.util.ConcurrentModificationException 并发修改异常
/**
* 解决方案:
* 1,List<String> strings = new Vector<>();
* 2.List<String> strings = Collections.synchronizedList(new ArrayList<>());
* 3.List<String> strings = new CopyOnWriteArrayList<>();
*/
//
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);
},"线程-"+i).start();
}
}
}
Set 不安全
public class TestSet {
public static void main(String[] args) {
//java.util.ConcurrentModificationException
/**
*1、Set<String> set = Collections.synchronizedSet(new HashSet<>());
*/
//Set<String> set = new HashSet<>();
Set<String> set = new CopyOnWriteArraySet<String>();
for (int i = 1; i <= 30; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
},"线程-"+i).start();
}
}
}
Map
// map 是这样用的吗? 不是,工作中不用 HashMap
// 默认等价于什么? new HashMap<>(16,0.75);
// Map<String, String> map = new HashMap<>();
// 研究ConcurrentHashMap的原理
new ConcurrentHashMap<>();
6,Callable
与Runnable有什么不同
1、可以有返回值
2、可以抛出异常
3、方法不同,run()/ call()
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyThread myThread = new MyThread();
FutureTask futureTask = new FutureTask(myThread);
//futureTask 是runable的实现类
new Thread(futureTask,"A").start();
new Thread(futureTask,"B").start();
String s = (String) futureTask.get(); //这个get方法可能会产生阻塞!把他放在最后
System.out.println(s);
// ExecutorService executorService = Executors.newFixedThreadPool(3);
// executorService.submit(futureTask);
// executorService.shutdown();
}
}
class MyThread implements Callable<String> {
@Override
public String call() {
System.out.println("call");// 只打印一个call 因为有缓存
return "wwww";
}
}
注意细节:
1、有缓存
2、结果可能需要等待,会阻塞
7,常用的辅助类
7.1 CountDownLatch
![](https://candoit.top/wp-content/uploads/2020/12/image-20201203180929448-1024x371.png)
public class sub {
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()+" gogo ");
countDownLatch.countDown();//数量减一
},String.valueOf(i)).start();
}
countDownLatch.await();// 等待计数器归零,然后再向下执行
System.out.println("close door");
}
}
7.2 CyclicBarrier
public class add {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("收集到7!");
});
for (int i = 0; i < 8; i++) {
final int temp = i;
new Thread(()->{
try {
cyclicBarrier.await(); //等待
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("执行"+temp);
}).start();
}
}
}
8.3、Semaphore
public class SemaphoreTest {
public static void main(String[] args) {
//线程数量 停车位 6车3停车位
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();
}
},"线程--"+i).start();
}
}
}
原理:
semaphore.acquire() 获得,假设如果已经满了,等待,等待被释放为止!
semaphore.release(); 释放,会将当前的信号量释放 + 1,然后唤醒等待的线程!
作用: 多个共享资源互斥的使用!并发限流,控制最大的线程数!
8,读写锁
9,阻塞队列
BlockingQueue
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gLvUvLTJ-1607392386179)(C:\Users\胡歌\AppData\Roaming\Typora\typora-user-images\image-20201203183738266.png)]
四组API
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KnQfPr4m-1607392386180)(C:\Users\胡歌\AppData\Roaming\Typora\typora-user-images\image-20201203183414023.png)]
public class TestBQ {
public static void main(String[] args) throws InterruptedException {
test4();
}
/**
* 抛出异常
*/
public static void test1(){
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<String>(3);
System.out.println(blockingQueue.add("1"));
System.out.println(blockingQueue.add("2"));
System.out.println(blockingQueue.add("3"));
//System.out.println(blockingQueue.add("4"));
//IllegalStateException: Queue full 抛出异常
System.out.println(blockingQueue.element());//查看首元素是谁
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//System.out.println(blockingQueue.remove());
//java.util.NoSuchElementException 抛出异常
}
/**
* 有返回值,没有异常
*/
public static void test2(){
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<String>(3);
System.out.println(blockingQueue.offer("1"));
System.out.println(blockingQueue.offer("2"));
System.out.println(blockingQueue.offer("3"));
System.out.println(blockingQueue.offer("4"));
// 不抛出异常 返回false
System.out.println(blockingQueue.peek());//检测队首元素
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
// 不抛出异常 返回null
}
/**
* 等待。阻塞(一直注释)
*/
public static void test3() throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<String>(3);
//一直阻塞
blockingQueue.put("1");
blockingQueue.put("2");
blockingQueue.put("3");
//blockingQueue.put("4");//队列没有位置了,一直阻塞
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<String>(3);
blockingQueue.offer("1");
blockingQueue.offer("2");
blockingQueue.offer("3");
blockingQueue.offer("4", 2,TimeUnit.SECONDS);//超过两秒就退出
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
blockingQueue.poll(2,TimeUnit.SECONDS);
}
}
10,线程池
线程池:三大方法、7大参数、4种拒绝策略
优点
1、降低资源的消耗
2、提高响应的速度
3、方便管理。
三大方法
![](https://candoit.top/wp-content/uploads/2020/12/image-20201203185916843.png)
七大参数
四种拒绝策略
11,JMM
volatile
Volatile 是java虚拟机提供轻量级的同步机制
1,保证可见性
2,不保证原子性
3,禁止指令重排
什么是JMM
JMM:java内存模型,不存在的东西,概念!
关于JMM的同步约定
1,线程解锁前,必须把共享变量立刻刷回主存
2,线程加锁前,必须读取主存中的最新值到工作内存中
2,加锁和解锁是同一把锁
内存交互操作
内存交互操作有8种,虚拟机实现必须保证每一个操作都是原子的,不可在分的(对于double和long类型的变量来说,load、store、read和write操作在某些平台上允许例外)
-
- lock (锁定):作用于主内存的变量,把一个变量标识为线程独占状态
- unlock (解锁):作用于主内存的变量,它把一个处于锁定状态的变量释放出来,释放后的变量才可以被其他线程锁定
- read (读取):作用于主内存变量,它把一个变量的值从主内存传输到线程的工作内存中,以便随后的load动作使用
- load (载入):作用于工作内存的变量,它把read操作从主存中变量放入工作内存中
- use (使用):作用于工作内存中的变量,它把工作内存中的变量传输给执行引擎,每当虚拟机遇到一个需要使用到变量的值,就会使用到这个指令
- assign (赋值):作用于工作内存中的变量,它把一个从执行引擎中接受到的值放入工作内存的变量副本中
- store (存储):作用于主内存中的变量,它把一个从工作内存中一个变量的值传送到主内存中,以便后续的write使用
- write (写入):作用于主内存中的变量,它把store操作从工作内存中得到的变量的值放入主内存的变量中
JMM对这八种指令的使用,制定了如下规则:
-
- 不允许read和load、store和write操作之一单独出现。即使用了read必须load,使用了store必须write
- 不允许线程丢弃他最近的assign操作,即工作变量的数据改变了之后,必须告知主存
- 不允许一个线程将没有assign的数据从工作内存同步回主内存
- 一个新的变量必须在主内存中诞生,不允许工作内存直接使用一个未被初始化的变量。就是怼变量实施use、store操作之前,必须经过assign和load操作
- 一个变量同一时间只有一个线程能对其进行lock。多次lock后,必须执行相同次数的unlock才能解锁
- 如果对一个变量进行lock操作,会清空所有工作内存中此变量的值,在执行引擎使用这个变量前,必须重新load或assign操作初始化变量的值
- 如果一个变量没有被lock,就不能对其进行unlock操作。也不能unlock一个被其他线程锁住的变量
- 对一个变量进行unlock操作之前,必须把此变量同步回主内存
12,volatile
保证可见性
public class JMMDemo { // 不加 volatile 程序就会死循环! // 加 volatile 可以保证可见性
private volatile static int num = 0;
public static void main(String[] args) { // main
new Thread(() -> { // 线程 1 对主内存的变化不知道的
while (num == 0) {
}
}).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
num = 1;
System.out.println(num);
}
}
不保证原子性
// volatile 不保证原子性
public class VDemo02 { // volatile 不保证原子性
private volatile static int num = 0;
public static void add() {
num++;
}
public static void main(String[] args) {
//理论上num结果应该为 2 万
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 ,怎么样保证原子性
使用原子类,解决 原子性问题
import java.util.concurrent.atomic.AtomicInteger;
// volatile 不保证原子性
public class VDemo02 {
// volatile 不保证原子性
// 原子类的 Integer
private volatile static AtomicInteger num = new AtomicInteger();
public static void add(){
// num++; // 不是一个原子性操作
num.getAndIncrement(); // AtomicInteger + 1 方法, CAS
}
public static void main(String[] args) {
//理论上num结果应该为 2 万
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);
}
}
禁止指令重排
什么是 指令重排:你写的程序,计算机并不是按照你写的那样去执行的。
源代码–>编译器优化的重排–> 指令并行也可能会重排–> 内存系统也会重排—> 执行
处理器在进行指令重排的时候,考虑:数据之间的依赖性!
int x = 1; // 1
int y = 2; // 2
x = x + 5; // 3
y = x * x; // 4
我们所期望的:1234 但是可能执行的时候回变成 2134 1324 可不可能是 4123!
volatile 可以避免指令重排:
内存屏障。CPU指令。作用:
1、保证特定的操作的执行顺序!
2、可以保证某些变量的内存可见性 (利用这些特性volatile实现了可见性)
13,死锁
产生死锁的四个必要条件:
1.互斥条件:一个资源每次只能被一个进程使用。
2.请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
3.不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺。
4.循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。