JUC并发包学习

1、什么是JUC

java.util工具包、包、分类

业务:普通的线程代码 Thread

Runable:没有返回值、效率相对于Callable相对较低。

2、线程和进程

进程:一个程序。如:QQ.exe。

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

JAVA默认有几个线程?2个 mian、GC

线程:开了一个进程Typora,写字,自动保存(单独的一条线程去做自动保存)

对于JAVA而言:Thread、Runable、Callable

JAVA真的可以开启线程吗? 开不了

public synchronized void start() {
    /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
     */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. */
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}
//本地方法、底层的C++操作,JAVA无法直接操作硬件
private native void start0();

并发、并行

并发编程:并发、并线

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

  • CPU一核,模拟出来多个线程,

并行(多个人一起行走)

CPU多核,多个线程可以同时执行;线程池去做

package com.study.juc.demo01;

public class Test1 {
    public static void main(String[] args) {
        //获取CPU的核树
        //CPU密集型、IO密集型
       System.out.println(Runtime.getRuntime().availableProcessors());
    }
}

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

线程有几个状态 6个

public enum State {
    //线程新生
    NEW, 

    //运行
    RUNNABLE,

    //阻塞
    BLOCKED,

    //等待
    WAITING,

    //超时等待,过期不候
    TIMED_WAITING,

    //终止
    TERMINATED;
}

wait/sleep 区别

  1. 来自不同的类

    wait=>Object

    sleep=>Thread

  2. 关于锁的释放

    wait会释放锁,sleep睡觉了,抱着锁睡觉,不会释放

  3. 使用的范围是不通的

    wait必须在同步代码块当中

  4. 是否需要捕获异常

    wait不需要捕获异常

    sleep必须要捕获异常

3、Lock(重点)

传统的synchronized

package com.study.juc.demo01;

//基本的卖票例子

/**
 * 真正的多线程开发,公司的开发,要降低耦合性
 * 线程就是一个单独的资源类,没有任何附属的操作
 * 1、属性、方法
 */
public class SaleTicketDemo01 {
    public static void main(String[] args) {
        //并发:多个线程操作同一个资源类
        Ticket ticket = new Ticket();
        //FunctionalInterface 函数式接口   jdk1.8  lambda表达式   (参数)->{方法体}
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 1; 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);
        }
    }
}

Lock

公平锁:十分公平,要先来后到

非公平锁:十分不公平,可以插队

package com.study.juc.demo01;

//基本的卖票例子

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

/**
 * 真正的多线程开发,公司的开发,要降低耦合性
 * 线程就是一个单独的资源类,没有任何附属的操作
 * 1、属性、方法
 */
public class SaleTicketDemo02 {
    public static void main(String[] args) {
        //并发:多个线程操作同一个资源类
        Ticket2 ticket = new Ticket2();
        //FunctionalInterface 函数式接口   jdk1.8  lambda表达式   (参数)->{方法体}
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        }, "C").start();

    }
}

/**
 * Lock三部曲
 * 1、newReentrantLock()
 * 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) {
        } 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版

package com.study.juc.producerconsumer;

/**
 * 线程之间的通信问题:生产者与消费组问题   等待唤醒和通知
 * 线程交替执行  AB操作同一个变量   num=0
 * A  num+1
 * B  num-1
 */
public class Test1 {
    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 number = 0;

    //+1
    public synchronized void increment() throws InterruptedException {
        if (number != 0) {
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        //通知其他线程,我+1完毕了
        this.notifyAll();
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
        if (number == 0) {
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        //通知其他线程,我-1完毕了
        this.notifyAll();
    }
}

问题存在:两个线程,但是4个线程的时候是有问题的。这个时候是因为if的愿意,在线程当中应该使用while

if判断一次就不走了,而while不停的去循环监视

1643179965310

package com.study.juc.producerconsumer;

/**
 * 线程之间的通信问题:生产者与消费组问题   等待唤醒和通知
 * 线程交替执行  AB操作同一个变量   num=0
 * A  num+1
 * B  num-1
 */
public class Test2 {
    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 number = 0;

    //+1
    public synchronized void increment() throws InterruptedException {
        while (number != 0) {
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        //通知其他线程,我+1完毕了
        this.notifyAll();
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
        while (number == 0) {
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        //通知其他线程,我-1完毕了
        this.notifyAll();
    }
}

JUC的生产者和消费组问题

1643180444768

代码实现

package com.study.juc.producerconsumer;

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

/**
 * 线程之间的通信问题:生产者与消费组问题   等待唤醒和通知
 * 线程交替执行  AB操作同一个变量   num=0
 * A  num+1
 * B  num-1
 */
public class Test3 {
    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 Data3 {//数字 资源类
    private int number = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    //condition.await();   //等待
    //condition.signalAll(); //唤醒全部
    //+1
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) {
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            //通知其他线程,我+1完毕了
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //-1
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (number == 0) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            //通知其他线程,我-1完毕了
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}

任何一个新的技术,绝对不是仅仅只是覆盖了原先的技术,肯定有优势和补充

Condition精准的唤醒和通知 A执行完B执行,B执行完D执行,有序进行执行

package com.study.juc.producerconsumer;

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

/**
 * A执行完调用B,B执行完调用C,C执行完调用A
 */
public class Test4 {
    public static void main(String[] args) {
        Data4 data4 = new Data4();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data4.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data4.printB();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data4.printC();
            }
        }, "C").start();

    }


}

class Data4 {
    private Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    private int number = 1; //1 A执行,2 B执行,3 C执行

    public void printA() {
        lock.lock();
        try {
            //业务,判断——》执行——》通知
            while (number != 1) {//判断
                //等待
                condition1.await();
            }
            //通知,通知指定的人
            System.out.println(Thread.currentThread().getName() + "=>AAAAAAAAAAA");
            number = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            while (number != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>BBBBBBBBBB");
            number = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (number != 3) {
                condition3.await();
            }
            number = 1;
            System.out.println(Thread.currentThread().getName() + "=>CCCCCCCCC");
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

5、8锁现象

锁是什么,如何判断锁的是谁

new this具体的一个对象

static class 是唯一一个class模板

可以去git上去看代码

6、集合类不安全

List不安全

package com.study.juc.unsafe;

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

//java.util.ConcurrentModificationException  多线程ArrayList插入数据会报此异常
public class ListTest {
    public static void main(String[] args) {
        //并发下ArrayList不安全的

        /**
         * 解决方案:
         * 1、List<String> list = new Vector<>();
         * 2、List<String> list = Collections.synchronizedList(new ArrayList<>());
         * 3、JUC的解决方案 List<String> list = new CopyOnWriteArrayList<>();
         */

//        List<String> list = new ArrayList<>();
        //CopyOnWrite  写入时复制,  COW:计算机程序设计领域的一种优化策略
        //多个线程调用的时候 List,读取的时候,是固定的,写入的时候是先复制再替换上去
        //在写入的时候,避免覆盖,造成数据问题

        //CopyOnWriteArrayList比Vector厉害在哪里?
        //Vector是synchronized的,有这个的基本效率会低,CopyOnWriteArrayList使用的lock
        List<String> list = new CopyOnWriteArrayList<>();

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

    }
}

Set

/**
 * 同理可证:java.util.ConcurrentModificationException
 * 1、 Set<String> set = Collections.synchronizedSet(new HashSet<>());
 * 2、 Set<String> set = new CopyOnWriteArraySet<>();
 */
public class SetTest {
    public static void main(String[] args) {
//        Set<String> set = new HashSet<>();
//        Set<String> set = Collections.synchronizedSet(new HashSet<>());
        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的底层是什么?

public HashSet() {
    map = new HashMap<>();
}
//add  本质就是map,保证键无法重复
public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}
	//PRESENT是一个不变的值
private static final Object PRESENT = new Object();

Map不安全

package com.study.juc.unsafe;

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


/**
 *java.util.ConcurrentModificationException
 */
public class MapList {

    public static void main(String[] args) {
        /**
         * map是这样用的吗? 不是?工作当中不用hashmap
         * 默认等价于new HashMap<>(16,0.75)
         */
//        Map<String, String> map = new HashMap<>();
        Map<String,String> map= new ConcurrentHashMap<>( );
        for (int i = 0; i < 30; i++) {

            int finalI = i;
            new Thread(() -> {
                map.put(String.valueOf(finalI),UUID.randomUUID().toString().substring(0, 5));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }
}

7、Callable

Callable接口类似于Runable,因为他们都是为其实例可能由另一个线程执行的设计。然而,Runable不返回结果,也不能抛出被检测的异常,Callable可以。

1、可以有返回值

2、可以抛出异常

3、方法不同 runable是run,callable是call

package com.study.juc.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(new Runnable()).start();
        //new Thread(new FutureTask<V>()).start();
        //new Thread(new FutureTask<V>(Callable)).start();
        MyThread thread=new MyThread();
        FutureTask futureTask=new FutureTask(thread); //设备类
        new Thread(futureTask,"A").start();
        String o = (String) futureTask.get();//获取Callable的返回结果     这个get方法可能产生阻塞,所以把他放在最后
        //或者使用异步通信来处理
        System.out.println(o);

    }
}

class MyThread implements Callable<String>{

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public String call() throws Exception {
        //在此中间有可能有耗时操作
        return "hello word";
    }
}

细节:有缓存、结果可能需要等待、会阻塞

8、常用的辅助类

8.1ConutDownLatch(减法计数器)

1643261822743

package com.study.juc.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 = 1; i <= 6; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " GO OUT");
                countDownLatch.countDown(); //计数器减一
            }, String.valueOf(i)).start();
        }
        countDownLatch.await();;//等待计数器归0
        System.out.println("关闭");
    }
}

原理:

countDownLatch.countDown(); //数量减1

countDownLatch.await(); //等待计数器归零,然后再向下执行。

每次调用线程countDown()数量减去1,假设计数器变为0,countDownLatch.await()就会被唤醒,继续执行后续操作。

8.2 CyclicBarrier(加法计数器)

1643340866600

package com.study.juc.add;

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

//加法计数器
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        /**
         * 集齐7颗龙珠召唤神龙
         */
        //召唤龙珠得线程
        //如果一直没有达到7个线程,他会一直运行。
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println("召唤神龙成功");
        });
        for (int i = 1; i <= 7; i++) {
            int finalI = i;
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 手机了" + finalI + "颗龙珠");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

8.3Semaphore

1643341390255

例子:抢车位! 6个车一共有3个停车位置

public class SemaphoreDemo {

    public static void main(String[] args) {
        //线程数量:停车位  (一共有3个线程,也就是一共有3个停车位) 限流 (一功能进来3个)
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; 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(); //释放
                }

            }, String.valueOf(i)).start();
        }
    }

原理:

semaphore.acquire() 获得,假设如果已经满了,需要等待,等待被释放为止
semaphore.release() 释放,会将当前的的信号量释放+1,然后唤醒等待的线程!

作用:多个共享资源互斥的使用!并发限流,控制最大的线程数。

9、读写锁

读可以被多个线程同时读,写的时候只能有一个线程去写,提高了程序的性能

package com.study.juc.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 独占锁(写锁) 一次只能被一个线程占有
 * 共享锁(读锁) 多个线程可以同时占有   
 *  ReadWriteLock 会有三种情况
 *  1、读-读   可以同时操作共存
 *  2、读-写   不能同时操作共存
 *  3、写-写   不能同时操作共存
 *
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();

        //写入
        for (int i = 1; i <= 5; i++) {
            int temp = i;
            new Thread(() -> {
                myCache.put(temp + "", temp + "");
            }, String.valueOf(i)).start();
        }
        //读取
        for (int i = 1; i <= 5; i++) {
            int temp = i;
            new Thread(() -> {
                myCache.get(temp + "");
            }, String.valueOf(i)).start();
        }
    }
}


//自定义缓存
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() + "写入OK ");
        } 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);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取OK ");
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            readWriteLock.readLock().unlock();
        }

    }
}


//自定义缓存
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() + "写入OK ");

    }

    //读  取
    public void get(String key) {
        System.out.println(Thread.currentThread().getName() + "读取" + key);

        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName() + "读取OK ");

    }
}

10、阻塞队列

队列的特点:先进先出 FIFO

写入:如果队列满了,就必须阻塞等待取走后再进行写入

取:如果队列是空的,就必须等待生产才能取

BlockingQueue不是新的东西

1644376582520

什么情况下我们会使用阻塞队列:多线程并发处理,线程池。

如何使用队列:

4组API

方式 抛出异常 不抛出异常,有返回值 阻塞等待 超时等待
添加 add offer() put offer(,,)
移除 remove poll() take poll(,,)
是否为首行 element peek

1、抛出异常

2、不抛出异常

3、阻塞等待

4、超时等待

/**
 * 抛出异常
 */
public static void  test1(){
    //队列的大小
    ArrayBlockingQueue<Object> 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("============================");//

    Object element = blockingQueue.element();  //element查看队首元素
    System.out.println(blockingQueue.remove());
    System.out.println(blockingQueue.remove());
    System.out.println(blockingQueue.remove());
    //移除的时候队列当中没有元素还在继续移除,抛出此异常java.util.NoSuchElementException
    System.out.println(blockingQueue.remove());
}

/**
 * 不抛出异常
 */
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"));
    // System.out.println(blockingQueue.offer("d"));  //不抛出异常
    Object peek = blockingQueue.peek();//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<Object> 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()); //队列中没有元素后,要是取得情况下,也会一直阻塞到这

}
/**
 * 等待,阻塞(等待超时)
 */
public static void  test4() throws InterruptedException {
    //队列的大小
    ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);

    //一直阻塞
    System.out.println(blockingQueue.offer("a", 1, TimeUnit.SECONDS));
    System.out.println(blockingQueue.offer("b", 1, TimeUnit.SECONDS));
    System.out.println(blockingQueue.offer("c", 1, TimeUnit.SECONDS));
  //  System.out.println(blockingQueue.offer("d", 1, TimeUnit.SECONDS));
    // blockingQueue.offer("d",1, TimeUnit.SECONDS);  //队列没有位置,1秒后如果还没有位置,则自动退出
    System.out.println(blockingQueue.poll(1,TimeUnit.SECONDS));
    System.out.println(blockingQueue.poll(1,TimeUnit.SECONDS));
    System.out.println(blockingQueue.poll(1,TimeUnit.SECONDS));
    System.out.println(blockingQueue.poll(1,TimeUnit.SECONDS));
    //System.out.println(blockingQueue.poll(1,TimeUnit.SECONDS)); //队列中没有元素后,1秒后如果还没有元素,则自动退出
}

SynchronousQueue 同步队列、没有容量

进去一个元素,必须等待取出来后才能再往里面放一个元素,相当于最多只能放一个元素

/**
 * 同步队列
 * 和其他的BlockingQueue不一样,SynchronousQueue不存储元素
 * put了一个元素,必须从里面先take取出来,否则put不进去值
 */
public class SynchronousQueueDemo {
    public static void main(String[] args) {
        SynchronousQueue 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() + " take=>" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + " take=>" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + " take=>" + synchronousQueue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T2").start();
    }

}

11、线程池(重点)

线程池:三大方法、7大参数、4中拒绝模式

线程池的好处

  1. 降低资源的消耗

  2. 提高响应的速度

  3. 方便管理

    线程复用、控制并发数、管理线程

线程

线程池不允许使用Executors,去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的允许规则,规避资源耗尽的风险

说明:Executors返回的线程池对象的弊端如下:

1)FixedThreadPool和SingleThreadPool:

允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM。

2)CachedThreadPool和ScheduledThreadPool:

允许的创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致OOM。

线程的三大方法

/**
 * Executors 工具类,三大方法
 * 使用了线程池之后,使用线程池来创建线程
 */
public class Demo1 {
    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++) {
                //使用了线程池之后,使用线程池创建线程
                threadPool.execute(
                        () -> {
                            System.out.println(Thread.currentThread().getName() + "    OK");
                        }
                );
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //线程池用完 ,线程池结束要关闭
            threadPool.shutdown();
        }
    }
}

7大参数

源码分析:

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,	//Integer.MAX_VALUE 约等于21亿
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}

//本质都是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.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

手动创建一个线程池

public class Demo2 {
    public static void main(String[] args) {
        LinkedBlockingQueue queue = new LinkedBlockingQueue(3);
        //最大的线程到底如何定义
        //1、CPU密集型     几核,就是几,可以保持CPU的效率最高 (大量的计算)
        //2、IO密集型 判断你程序中十分IO的线程有多少个,最大线程数就设置为多少(涉及到网络、磁盘IO的任务都是IO密集型)
        ExecutorService threadPool = new ThreadPoolExecutor(2,5,3, TimeUnit.SECONDS,queue,Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());

        try {
            //最大承载Deque和maxPoolSize
            //超过最大线程数RejectedExecutionException
            for (int i = 0; i <=9; i++) {
                //使用了线程池之后,使用线程池创建线程
                threadPool.execute(
                        () -> {
                            System.out.println(Thread.currentThread().getName() + "    OK");
                        }
                );
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //线程池用完 ,线程池结束要关闭
            threadPool.shutdown();
        }
    }
}

4种拒绝策略

/**
 * new ThreadPoolExecutor.AbortPolicy()  银行人员满了,可是还有人来,这个时候不处理这个人的,直接抛出异常 拒绝后的异常为:RejectedExecutionException
 * new ThreadPoolExecutor.CallerRunsPolicy()  哪里来的去哪,但是不爆出异常
 * new ThreadPoolExecutor.DiscardOldestPolicy() 队列满了会尝试去跟最早的竞争,不会抛出异常
 *  new ThreadPoolExecutor.DiscardPolicy() 队列满了不会抛出异常
 */

1644393032485

12、四大函数式接口(必须掌握)

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

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

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}
//函数是接口:FunctionalInterface 简化编程模型,在新版本的框架底层大量使用
//foreach就是一个函数式接口

函数式接口

package com.study.juc.function;

import java.util.function.Function;

/**
 * Function 函数型接口,有一个输入参数,有一个输出
 * 只要是函数型接口 可以用Lambda表达式简化
 */
public class Demo1 {
        public static void main(String[] args) {
        //工具类: 输出输入的值
        Function function = new Function<String,String>() {
            @Override
            public String apply(String  str) {
                return str;
            }
        };
        System.out.println(function.apply("1111"));
    }
    public static void main(String[] args) {
        Function function = (str) -> {
            return str;
        };
        System.out.println(function.apply("ceshi"));
    }
}

断定型接口 :有一个输入参数,返回值只能是bool值

/**
 * 断定型接口;有一个输入参数,返回值式布尔值
 */
public class Demo2 {
    //        public static void main(String[] args) {
//        Predicate<String> predicate = new Predicate<String>() {
//            @Override
//            public boolean test(String s) {
//                return s.isEmpty();
//            }
//        };
//    }
    public static void main(String[] args) {
        Predicate<String> predicate = s -> { return s.isEmpty();};
    }
}

消费型接口

/**
 * Consumer  消费型接口,只有输入,没有返回值
 */
public class Demo3 {
    public static void main(String[] args) {
        Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };
    }

    public static void main(String[] args) {
        Consumer<String> consumer=(s -> {System.out.println(s);});
        consumer.accept("测试");
    }
}

供给型接口

/**
 * Supplier供给型接口
 */
public class Demo4 {
    public static void main(String[] args) {
        Supplier<String> supplier = new Supplier<String>() {
            @Override
            public String get() {
                return "测试";
            }
        };
        System.out.println(supplier.get());
    }
    public static void main(String[] args) {
        Supplier<String> supplier = () -> { return "测试";};
        System.out.println(supplier.get());
    }
}

13、Stream流式计算

package com.study.juc.stream;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 题目要求:一分钟完成此题,只能用一行代码实现
 * 现在有5个用户!筛选:
 * 1、ID必须式偶数
 * 2、年龄必须大于23岁
 * 3、用户名转为大写字母
 * 4、用户名字母倒叙排列
 * 5、只能输出一个用户
 */
public class Test1 {

    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);
        User u6 = new User(6, "f", 26);
        List<User> users = Arrays.asList(u1, u2, u3, u4, u5, u6);
        users.stream().filter(w -> w.getId() % 2 == 0)
                .filter(w -> w.getAge() > 23)
                .map(w -> w.getName().toLowerCase())
                .sorted((uu1, uu2) -> uu2.compareTo(uu1))
                .limit(1).forEach(System.out::println);
    }
}

@Data
@AllArgsConstructor
class User {
    private Integer id;
    private String name;
    private Integer age;
}

14、ForkJoin

什么是ForkJoin

ForkJoin在JDK1.7,并行执行任务!提高效率,适用于大数据量的时候

大数据当中:Map Reduce(将大任务拆分为小任务)

1644457815696

ForkJoin特点:工作窃取,可以提高效率。A、B两个线程,B线程执行的快,A线程执行的慢,当B线程执行完后会去A线程里面窃取一个任务去执行。

A、B他就是一个双端队列,也就是两端(头部和尾部)都可以对队列进行操作

1644458022746

15、Futrue

package com.study.juc.future;

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

/**
 * 异步调用
 * AJAX
 * 1、异步执行
 * 2、成功回调
 * 3、失败回调
 */
public class Demo01 {
    //没有返回值的runAsync的异步回调
//    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        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("1111111");
//        completableFuture.get();//获取阻塞执行结果
//    }

    //有返回值的异步回调supplyAsync
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> completableFuture=CompletableFuture.supplyAsync(()->{
            System.out.println(Thread.currentThread().getName()+"supplyAsync=>Integer");
            int o=1/0;
            return  1024;
        });

        completableFuture.whenComplete((t,u)->{
            System.out.println("t=>"+t);  //t代表正常的返回结果
            System.out.println("u=>"+u);  //u代表错误的信息 u=>java.util.concurrent.CompletionException:

        }).exceptionally((e)->{
            System.out.println(e.getMessage());
            return 233;
        }).get();

    }

}

16、JMM

请你谈谈你对volatile的看法

Volatile是虚拟机提供轻量级的同步机制

1、保证可见性

2、不保证原子性

3、禁止指令重排

什么是JMM?

JMM 是Java内存模型,不存在的东西,他就是一个概念,约定。

关于JMM一些同步的约定:

1、线程解锁之前,必须把共享变量立刻刷回主内存当中。

2、线程加锁之前,必须读取主内存中的最新值到线程的本地内存当中

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

线程:工作内存、主存

8个操作

1644479080796

内存交互操作

引用于

  内存交互操作有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操作之前,必须把此变量同步回主内存

  JMM对这八种操作规则和对volatile的一些特殊规则就能确定哪里操作是线程安全,哪些操作是线程不安全的了。但是这些规则实在复杂,很难在实践中直接分析。所以一般我们也不会通过上述规则进行分析。更多的时候,使用java的happen-before规则来进行分析。

共享内存模型指的是JAVA内存模型,简称JMM,JMM决定一个线程对共享变量的写入时,能对另一个线程可见。共享变量放在主内存中,每个线程都有自己的本地内存,当多个线程同时访问一个数据的时候,可能本地内存没有及时刷新到主内存,所以就会发生线程安全的问题,这个时候就有volatile了

17、Volatile

1、保证可见性

//不加volatile程序就会死循环。 没有通知主内存num值已经变为0
//家volatile可以保证可见性
private static volatile int num = 0;

public static void main(String[] args) throws InterruptedException {
    new Thread(() -> {//线程1 对主内存的变化不知道
        while (num==0)
        {
        }
    },"线程一").start();
    TimeUnit.SECONDS.sleep(1);
    num=1;
    System.out.println(num);
}

2、不保证原子性

原子性:不可分割

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

1644481573452

一般num++这种操作使用原子类去操作。

package com.study.juc.tvolatile;

import java.util.concurrent.atomic.AtomicInteger;

//不保证原子性
public class VDemo2 {
    //volatile不保证原子性
//    private volatile static int num = 0;
    private volatile static AtomicInteger num = new AtomicInteger(0);

    public  static void add() {
        //num++; //不是原子性操作
        num.getAndIncrement();//+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) //java 有两个线程是默认存在的分别为:main和GC
        {
            Thread.yield();
        }
        System.out.println(num);
    }
}

这些类的底层都直接和操作系统挂钩,在内存中修改值!Unsafe是一个很特殊的存在。

指令重排

什么是指令重拍:你写的程序,计算机并不是按照你的那样去执行的。

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

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

非计算机专业

volatile可以避免指令重排:

内存屏障。CPU指令。作用:

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

2、可以保证某些变量的内存可见性

1644483147440

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

18、单例模式

饿汉式单例模式

/**
 * 饿汉式单列
 */
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;
    }
}

懒汉式单列模式

package com.study.juc.single;

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

/**
 * 懒汉式
 * <p>
 * 单线程没有问题
 * public static LazyMan getInstance() {
 * if (LAZY_MAN == null) {
 * LAZY_MAN = new LazyMan();
 * }
 * return LAZY_MAN;
 * }
 *
 *
 * 道高一尺魔高一丈
 */
public class LazyMan {
    private static boolean flag = false;

    public LazyMan() {
        synchronized (LazyMan.class) {   //synchronized只采取这一种方式,对象都用反射进行创建也会出现创建两次。 需要再配合一个变量执行,列如:红绿灯
            if (!flag) {
                flag = true;
            } else {
                throw new RuntimeException("不要试图使用反射来进行破坏");
            }
            System.out.println(Thread.currentThread().getName() + "ok");
        }
    }

    public static volatile LazyMan LAZY_MAN;

    //双重检测懒汉式的 懒汉式单列 DCL懒汉式
    public static LazyMan getInstance() {
        if (LAZY_MAN == null) {
            synchronized (LazyMan.class) {
                if (LAZY_MAN == null) {
                    LAZY_MAN = new LazyMan(); //不是原子性操作
                    /**
                     * 1、分配内存空间
                     * 2、执行构造方法,初始化对象
                     * 3、把这个对象指向这个空间
                     *
                     * 执行顺序有可能是123,也有能为132.
                     * 这个时候多线程的时候就会出现指令重拍, A线程创建完成后把这个对象还没有指向这个空间的时候,锁已经释放。 这个时候下一个线程已经过来了,判断的时候已经判断出
                     * LAZY_MAN还有没有为空。
                     */
                }
            }
        }
        return LAZY_MAN;
    }

    //多线程并发的时候如果没有使用synchronized 就会出现问题,创建多次。
//    public static void main(String[] args) {
//        for (int i = 0; i <= 20; i++) {
//            new Thread(() -> {
//                LazyMan.getInstance();
//            }, String.valueOf(i)).start();
//
//        }
//    }

    //反射可以破坏这种单列    反射不能破坏枚举
    public static void main(String[] args) throws Exception {
        // LazyMan lazyMan = LazyMan.getInstance();
        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);//无视私有的构造器
        Field flag = LazyMan.class.getDeclaredField("flag");
        LazyMan lazyMan1 = declaredConstructor.newInstance();
        flag.set(lazyMan1,false);
        LazyMan lazyMan = declaredConstructor.newInstance();

        System.out.println(lazyMan);
        System.out.println(lazyMan1);
        System.out.println(lazyMan == lazyMan1);
        System.out.println(lazyMan.equals(lazyMan1));

    }
}

静态内部类

package com.study.juc.single;

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

    private Holder(){

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

        private static final Holder HOLDER=new Holder();

    }
}

单列不安全,因为有反射,所以采取枚举

package com.study.juc.single;

//enum 是一个什么? 本身也是一个class类

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

public enum EnumSingle {
    INSTANCE;

    public EnumSingle getInstance() {
        return INSTANCE;
    }


}

class Test{
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        EnumSingle instance = EnumSingle.INSTANCE;
        Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class, int.class);
        declaredConstructor.setAccessible(true);
        EnumSingle enumSingle = declaredConstructor.newInstance();
        System.out.println(instance);
        System.out.println(enumSingle);// java.lang.IllegalArgumentException: Cannot reflectively create enum objects
    }
}

枚举类型得最终反编译源码

1644545487439

1644545461069

19、深入了解CAS

什么是CAS

package com.study.juc.cas;

import java.util.concurrent.atomic.AtomicInteger;

public class CASDemo {
    //CAS compareAndSet :比较并交换。     compareAndSet和getAndIncrement的底层都是调用compareAndSwapInt方法。
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(2022);
        //第一参数:期望值,第二个参数:修改后得值
        //public final boolean compareAndSet(int expect, int update)
        //如果我期望得值达到了,那么就更新,否则不更新,CAS是CPU并发得原语也就是CPU的指令
        boolean b = atomicInteger.compareAndSet(2022, 2023);
        System.out.println(b);
        System.out.println(atomicInteger.get());
        boolean b1 = atomicInteger.compareAndSet(2022, 2023);


        System.out.println(b1);
        System.out.println(atomicInteger.get());

        atomicInteger.getAndIncrement();

    }
}

Unsafe类

1644546523675

1644547251934

1644547178089

CAS:比较当前工作内存中的值和主内存的值,如果这个值是期望的,那么则执行操作!如果不是就一直循环!

缺点:

  1. 循环会耗时
  2. 一次性只能保证一个共享变量的原子性
  3. ABA问题

CAS:ABA(狸猫换太子)

1644548378075

[^ ]: A线程要将值1改为2,但是这时候B线程执行的比较快,将值1改为3,又将3改为1. 而A线程不知情,接着直接把1改为2. 这就是所谓的ABA问题

package com.study.juc.cas;

import java.util.concurrent.atomic.AtomicInteger;

public class CASDemo {
    //CAS compareAndSet :比较并交换。     compareAndSet和getAndIncrement的底层都是调用compareAndSwapInt方法。
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(2022);
        //第一参数:期望值,第二个参数:修改后得值
        //public final boolean compareAndSet(int expect, int update)
        //如果我期望得值达到了,那么就更新,否则不更新,CAS是CPU并发得原语也就是CPU的指令
        //============捣乱的线程====================
        System.out.println(atomicInteger.compareAndSet(2022, 2023));
        System.out.println(atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(2023, 2022));
        System.out.println(atomicInteger.get());
        //============期望的线程====================
        System.out.println(atomicInteger.compareAndSet(2022, 8888));
        System.out.println(atomicInteger.get());
    }
}

20、原子引用

解决ABA问题

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

1644550643119

package com.study.juc.cas;

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

public class CASReferenceDemo {

    public static void main(String[] args) {
        //1就是初始版本号
        //AtomicStampedReference注意:如果泛型是包装类,注意引用
        //正常的业务操作泛型当中放入的都是一个对象   如果要是使用大的值比如操纵127的,提前声明变量,在参数当中放入变量
        AtomicStampedReference<Integer> atomicStampedReference=new AtomicStampedReference<>(1,1);
         new Thread(()->{
             int stamp = atomicStampedReference.getStamp();
             System.out.println("a1=>"+stamp);
             try {
                 TimeUnit.SECONDS.sleep(2);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
             System.out.println(atomicStampedReference.compareAndSet(1, 2, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
             System.out.println("a2=>"+atomicStampedReference.getStamp());

             System.out.println(atomicStampedReference.compareAndSet(2, 1, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
             System.out.println("a2=>"+atomicStampedReference.getStamp());

         },"A线程").start();
        //与乐观锁的原理相同
        new Thread(()->{
            int stamp = atomicStampedReference.getStamp();
            System.out.println("b1=>"+stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(atomicStampedReference.compareAndSet(1, 6, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
            System.out.println("b2=>"+atomicStampedReference.getStamp());



        },"A线程").start();

    }
}

21、各种锁的理解

1、公平锁、非公平锁

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

非公平锁:非常不公平。可以插队(默认都是非公平锁)

public ReentrantLock() {
    sync = new NonfairSync();  //默认是非公平锁
}
public ReentrantLock(boolean fair) {//可通过参数就行控制为:公平锁或非公平锁
    sync = fair ? new FairSync() : new NonfairSync();
}

2、可重入锁

可重入锁(递归锁),拿到了第一层的锁,就拿到了里面所以锁都已经拿到

synchronized

package com.study.juc.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");

    }
}

Lock

package com.study.juc.lock;

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

/**
 * synchronized
 */
public class Demo02 {
    public static void main(String[] args) {
        Phone1 phone = new Phone1();

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

class Phone1 {
    Lock lock = new ReentrantLock();
    public void sms() {

        lock.lock();  //细节问题:lock.lock();   lock.unlock();//lock锁必须配对,否则会死锁到里面。加几次锁必须解几次锁
        try {
            System.out.println(Thread.currentThread().getName() + "->sms");
            call();
        } catch (Exception e) {
        } finally {
            lock.unlock();
        }

    }

    public void call() {

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

3、自旋锁(spinlock)

不断去尝试,直到成功为止。

1644557554727

//自定义自旋锁
package com.study.juc.lock;

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

public class SpinLockDemo {

    AtomicReference<Thread> atomicReference=new AtomicReference<Thread>();
    //加锁
    public void myLock(){
        Thread thread=Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"==>myLock");
        //自旋锁
        while (!atomicReference.compareAndSet(null,thread)){
        }
    }

    //解锁

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


//测试自旋锁
package com.study.juc.lock;

import java.util.concurrent.TimeUnit;

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

        //底层使用自旋锁  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 {
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                spinLockDemo.myUnLock();
            }
        }, "T2").start();

    }
}

4、死锁

死锁是什么?

死锁概念及产生原理
概念: 多个并发进程因争夺系统资源而产生相互等待的现象。
原理: 当一组进程中的每个进程都在等待某个事件发生,而只有这组进程中的其他进程才能触发该事件,这就称这组进程发生了死锁。
本质原因:
1)、系统资源有限。
2)、进程推进顺序不合理。

死锁产生的4个必要条件
1、互斥: 某种资源一次只允许一个进程访问,即该资源一旦分配给某个进程,其他进程就不能再访问,直到该进程访问结束。
2、占有且等待: 一个进程本身占有资源(一种或多种),同时还有资源未得到满足,正在等待其他进程释放该资源。
3、不可抢占: 别人已经占有了某项资源,你不能因为自己也需要该资源,就去把别人的资源抢过来。
4、循环等待: 存在一个进程链,使得每个进程都占有下一个进程所需的至少一种资源。
当以上四个条件均满足,必然会造成死锁,发生死锁的进程无法进行下去,它们所持有的资源也无法释放。这样会导致CPU的吞吐量下降。所以死锁情况是会浪费系统资源和影响计算机的使用性能的。那么,解决死锁问题就是相当有必要的了。

解决问题

1、jps -l定位进程号x

E:\Study\JUC>jps -l
136256
239120 com.study.juc.lock.DeadLockDemo
225348 org.jetbrains.kotlin.daemon.KotlinCompileDaemon
239060 org.jetbrains.jps.cmdline.Launcher
237640 finalshell.jar
239816 sun.tools.jps.Jps


2、使用jstack 239120(进程号) 可以找到死锁的问题

关于文字中的代码都可以在git上去看到和下载。对于文章中的图片,上传太麻烦了,就不做上传了。
https://github.com/15201600156/JUC.git
本文学习是参考B站狂神说学习的。

posted @ 2022-02-11 14:37  —阿峰—  阅读(70)  评论(0编辑  收藏  举报