JUC并发编程

什么是JUC

java.util.concurrent*

public class Test1 {
    public static void main(String[] args) {
        //获取处理器核数
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}
com.antake.Test1
4
Process finished with exit code 0

回顾

线程有几个状态

public enum State {
        //新生
        NEW,
		//运行
        RUNNABLE,
    	//阻塞
        BLOCKED,
    	//等待
        WAITING,
    	//计时等待
        TIMED_WAITING,
    	//终止
        TERMINATED;
    }

wait/sleep区别

  1. 来自不同的类

    wait=>Object

    sleep=>Thread

  2. 关于锁的释放

    wait会释放锁,sleep不会释放锁

  3. 使用的范围不同

    wait必须在同步代码块中

    sleep可以在任何地方使用

  4. 是否需要捕获异常

    wait不需要捕获异常

    sleep必须要捕获异常

Lock锁

传统Synchronized

package com.antake;
//基本的卖票例子
/*
* 真正的多线程开发,公司中的开发,降低耦合性
* 线程就是一个单独的资源类,没人任何附属的操作
* 1.属性 2.方法
*/

public class SaleTicket01 {
    public static void main(String[] args) {
        //并发:多个线程操作同一个资源类,把资源类丢入线程
        Ticket ticket = new Ticket();
        //@FunctionalInterface函数式接口
        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接口

image-20200423144145507

image-20200423144247391

image-20200423144510021

公平锁:十分公平,可以先来后到

非公平锁:十分不公平,可以插队(默认)

package com.antake;
//基本的卖票例子
/*
 * 真正的多线程开发,公司中的开发,降低耦合性
 * 线程就是一个单独的资源类,没人任何附属的操作
 * 1.属性 2.方法
 */

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

public class SaleTicket02 {
    public static void main(String[] args) {
        Ticket02 ticket = new Ticket02();
        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 Ticket02{
    //属性,方法
    private int number=50;
    //卖票的方式
    //synchronized本质队列,排队,锁
    Lock lock=new ReentrantLock();
    public synchronized 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锁就不一定会等待下去 lock.tryLock();
  5. synchronized可重入锁,不可以中断,非公平;lock,可重入锁,可以判断锁,非公平(可以手动设置)
  6. synchronized适合锁少量的代码同步问题,lock适合锁大量的同步代码

生产者和消费者问题

synchronized版

package com.antake.pc;
/*线程只间的通信问题:生产者和消费者问题  等待唤醒,通知唤醒
线程交替执行,A B操作同一个变量 num=0
A num+1
B num-1
* */
public class A {
    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);
        this.notifyAll();

    }
    //-1
    public synchronized void decrement() throws InterruptedException {
        if (number==0){
           this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        this.notifyAll();
    }
}

问题存在,A,B,C,D 四个线程还安全吗

image-20200423151531901

image-20200423151758861

if改为while

package com.antake.pc;
/*线程只间的通信问题:生产者和消费者问题  等待唤醒,通知唤醒
线程交替执行,A B操作同一个变量 num=0
A num+1
B num-1
* */
public class A {
    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 number=0;
    //+1
    public synchronized void increment() throws InterruptedException {
        while (number!=0){
           this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        this.notifyAll();

    }
    //-1
    public synchronized void decrement() throws InterruptedException {
        while (number==0){
           this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        this.notifyAll();
    }
}

juc版的生产者和消费者问题

image-20200423154200737

通过lock可以找到condition

image-20200423154017410

代码实现

package com.antake.pc;

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

public class B {
    public static void main(String[] args) {
        DataB dataB = new DataB();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    dataB.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    dataB.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    dataB.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    dataB.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}

class DataB {
    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);
            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);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

condition精准的通知和唤醒线程

image-20200423155720060

package com.antake.pc;

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

/*
*
* */
public class C {
    public static void main(String[] args) {
        DataC dataC = new DataC();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                dataC.printA();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                dataC.printB();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                dataC.printC();
            }
        },"C").start();
    }
}
class DataC{
    private Lock lock=new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    private int number=1;
    public void printA(){
        lock.lock();
        try {
            while (number!=1){
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"==>AAAAA");
            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()+"==>BBBBB");
            number=3;
            condition3.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printC(){
        lock.lock();
        try {
            while (number!=3){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"==>CCCCCC");
            number=1;
            condition1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

image-20200423160820836

8锁现象

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

对象,class

package com.antake.lock8;

import java.util.concurrent.TimeUnit;

/*
8锁就是关于锁的八个问题
* */
public class Test1 {
    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(()->{
            phone.sendSms();
        },"A").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            phone.call();
        },"B").start();
    }
}
class Phone{
    //synchronized锁的是方法调用者
    // 两个方法用的是同一个锁,所以谁先拿到就是谁先执行
    public synchronized void sendSms(){
        System.out.println("sendSms");
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public synchronized void call(){
        System.out.println("call");
    }
}
package com.antake.lock8;

import java.util.concurrent.TimeUnit;

/*
8锁就是关于锁的八个问题
* */
public class Test2 {
    public static void main(String[] args) {
        Phone2 phone = new Phone2();
        Phone2 phone2 = new Phone2();
        new Thread(()->{
            phone.sendSms();
        },"A").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            phone2.call();
        },"B").start();
    }
}
class Phone2{
    //synchronized锁的是方法调用者
    // 两个方法用的是同一个锁,所以谁先拿到就是谁先执行
    public synchronized void sendSms(){
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("sendSms");
    }
    public synchronized void call(){
        System.out.println("call");
    }
    public void hello(){
        System.out.println("hello");
    }
}

package com.antake.lock8;

import java.util.concurrent.TimeUnit;

/*
8锁就是关于锁的八个问题
* */
public class Test3 {
    public static void main(String[] args) {
        Phone3 phone = new Phone3();
        Phone3 phone2 = new Phone3();
        new Thread(()->{
            phone.sendSms();
        },"A").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            phone.call();
        },"B").start();
    }
}
class Phone3{
    //synchronized锁的是方法调用者
    // 两个方法用的是同一个锁,所以谁先拿到就是谁先执行
    //static静态方法,类加载的时候就有了,锁的是class
    public static synchronized void sendSms(){
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("sendSms");
    }
    public static synchronized void call(){
        System.out.println("call");
    }
}

package com.antake.lock8;

import java.util.concurrent.TimeUnit;

/*
8锁就是关于锁的八个问题
* */
public class Test4 {
    public static void main(String[] args) {
        Phone4 phone = new Phone4();
        Phone4 phone2 = new Phone4();
        new Thread(()->{
            phone.sendSms();
        },"A").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            phone2.call();
        },"B").start();
    }
}
class Phone4{
    //synchronized锁的是方法调用者
    // 两个方法用的是同一个锁,所以谁先拿到就是谁先执行
    //static静态方法,类加载的时候就有了,锁的是class
    public static synchronized void sendSms(){
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("sendSms");
    }
    public synchronized void call(){
        System.out.println("call");
    }
}

小结

new this 具体的对象

static Class 唯一的模板

集合类不安全

List不安全

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.List<String> list =new CopyOnWriteArrayList<>();
        * */
        //CopyOnWrite写入时复制,COW计算机程序设计领域的一种优化策略
        //多线程调用的时候,list,读取的时候,固定的,写入(覆盖)
        //在写入的时候避免覆盖,造成数据问题
        //读写分离
        //CopyOnWriteArrayList比vector厉害在哪里?
        //因为vector使用了synchronized,而CopyOnWriteArrayList用的lock
        List<String> list =new CopyOnWriteArrayList<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(list);
            },String.valueOf(i+1)).start();
        }
    }
}

Set不安全

//同理java.util.ConcurrentModificationException
public class SetTest {
    public static void main(String[] args) {
        //并发下HashSet是不安全的
        /*
         * 怎么变得安全
         * 1.Set<String> set= Collections.synchronizedSet(new HashSet<>());
         * 2.Set<String> set=new CopyOnWriteArraySet<>();
         */
        //Set<String> set = 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+1)).start();
        }
    }
}

hashSet底层是什么?

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

Map不安全

为什么HashMap的加载因子是0.75,初始化容量是16?冲冲冲

常用ConcurrentHashMap,ConcurrentHashMap原理探究

    //map是这样用的吗?工作中不用hashmap
        //加载因子,初始化容量
    //默认等价于什么?加载因子=0.75 初始化容量=16
	//初始容量
	static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //初始因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    static final int TREEIFY_THRESHOLD = 8;
public class MapTest {
    public static void main(String[] args) {
        //同理java.util.ConcurrentModificationException
        /*
        * 如何解决
        * 1.Map<String, Object> map= Collections.synchronizedMap(new HashMap<>());
        * 2.Map<String, Object> map=new ConcurrentHashMap<>(); //并发hashmap
        * */
        // Map<String, Object> map = new HashMap<>();
        Map<String, Object> map=new ConcurrentHashMap<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
                System.out.println(map);
            },String.valueOf(i+1)).start();
        }
    }
}

Callable

image-20200424091631242

  1. 可以有返回值
  2. 可以抛出异常
  3. 方法不同,run()/ call()

代码测试

image-20200424095045268

image-20200424095350568

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();
        FutureTask futureTask = new FutureTask(new MyThread());
        new Thread(futureTask,"A").start();//怎么启动callable
        Integer o = (Integer) futureTask.get();
        System.out.println(o);
    }
}
class MyThread implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        return 123;
    }
}

细节:

  1. 有缓存
  2. 结果可能需要等待,会阻塞
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();
        FutureTask futureTask = new FutureTask(new MyThread());
        new Thread(futureTask,"A").start();//怎么启动callable
        new Thread(futureTask,"B").start();//结果会被缓存,提高效率
        Integer o = (Integer) futureTask.get();//这个get方法可能会产生阻塞,因为会等待返回的结果,一般放到最后,或者异步通信去拿
        System.out.println(o);
    }
}
class MyThread implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        return 123;
    }
}

常用的辅助类(必会)

CountDownLatch

image-20200424103025195

//计数器
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()+" Go Out");
                countDownLatch.countDown();//数量-1
            },String.valueOf(i+1)).start();
        }
        countDownLatch.await();//等待计数器归零,然后再向下执行
        System.out.println("FBI Closed The Door");
    }
}

原理:

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

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

每次有线程调用countDown()这个方法的时候就数量-1,假设计数器变为0,await激活,开始向下执行

CyclicBarrier

image-20200424104441855

加法计数器:

public class CyclicBarrierDemo {
    public static void main(String[] args) {
        /*
        * 七龙珠
        * */
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
            System.out.println("召唤神龙");
        });
        for (int i = 0; i < 7; i++) {
            final int temp=i;
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"收集到了"+(temp+1)+"个龙珠");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i+1)).start();
        }
    }
}

Semaphore

Semaphore:信号量

image-20200424114844554

public class SemaphoreDemo {
    public static void main(String[] args) {
        //线程数量
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    //添加许可证
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到车位");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName()+"离开车位");
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    //释放许可证
                    semaphore.release();
                }
            },String.valueOf(i+1)).start();
        }
    }
}

原理:

semaphore.acquire();获取,如果满了,就等待

semaphore.release();释放,将当前信号量释放,然后唤醒等待的线程

作用:多个线程互斥的使用!并发限流,控制线程数量

读写锁 ReadWriteLock

image-20200424132219334

package com.antake.readWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/*ReadWriteLock
(独占锁 写锁)一次只能有一个线程占有
(共享锁 读锁) 多个线程可以同时占有
* 读-读 可以共存
* 读-写 不能共存
* 写-写 不能共存
* */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();
        //写入
        for (int i = 0; i < 5; i++) {
            final int temp=i;
            new Thread(()->{
                myCache.put(String.valueOf(temp),temp);
            }).start();
        }
        //读取
        for (int i = 0; i < 5; i++) {
            final int temp=i;
            new Thread(()->{
                myCache.get(String.valueOf(temp));
            }).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()+"写入"+key+"ok");
    }
    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"读取"+key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取"+key+"ok"+o);
    }
}
//加锁的
class MyCacheLock{
    private volatile Map<String,Object> map=new HashMap<>();
    //读写锁,更加细粒度操作
    private ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
    //同时只能有一个线程写
    public void put(String key,Object value){
        //这里不同担心是不是同一个锁对象,因为源码里面给出来答案
        /*private final ReentrantReadWriteLock.ReadLock readerLock;
        *//** Inner class providing writelock *//*
        private final ReentrantReadWriteLock.WriteLock writerLock;*/
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"写入"+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入"+key+"ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
    public void get(String key){
        readWriteLock.readLock().lock();
        System.out.println(readWriteLock.readLock());
        try {
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取"+key+"ok"+o);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(readWriteLock.readLock());
            readWriteLock.readLock().unlock();
        }
    }
}

阻塞队列

阻塞队列:

image-20200424134512035

BlockingQueue BlockingQueue 不是新的东西

image-20200424150117021

image-20200424150328130

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

学会使用队列

四组api

方式 抛出异常 不会抛出异常,有返回值 阻塞 等待 超时等待
添加 add offer() put() offer("d",4, TimeUnit.SECONDS)
移除 remove poll() take() poll(4,TimeUnit.SECONDS)
检测队首元素 element peek - -
 	public static void test1(){
        //队列大小
        ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(3);
        System.out.println(arrayBlockingQueue.add("a"));
        System.out.println(arrayBlockingQueue.add("b"));
        System.out.println(arrayBlockingQueue.add("c"));
        //java.lang.IllegalStateException: Queue full 抛出异常
        //System.out.println(arrayBlockingQueue.add("d"));
        System.out.println("===========================");
        //查看队首元素是谁
        System.out.println(arrayBlockingQueue.element());

        System.out.println(arrayBlockingQueue.remove());
        System.out.println(arrayBlockingQueue.remove());
        System.out.println(arrayBlockingQueue.remove());
        //java.util.NoSuchElementException 抛出异常,队列为空
        //System.out.println(arrayBlockingQueue.remove());
    }
    public static void test2(){
        ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(3);
        System.out.println(arrayBlockingQueue.offer("a"));
        System.out.println(arrayBlockingQueue.offer("b"));
        System.out.println(arrayBlockingQueue.offer("c"));
        //System.out.println(arrayBlockingQueue.offer("d"));//false不抛出异常
        //查看队首元素是谁
        System.out.println(arrayBlockingQueue.peek());
        System.out.println(arrayBlockingQueue.poll());
        System.out.println(arrayBlockingQueue.poll());
        System.out.println(arrayBlockingQueue.poll());
        //不抛出异常 返回null
        System.out.println(arrayBlockingQueue.poll());
    }
    public static void test3() throws InterruptedException {
        ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);
        //一直阻塞
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        //没有位置一直阻塞
        //blockingQueue.put("c");
        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);
        blockingQueue.offer("a");
        blockingQueue.offer("b");
        blockingQueue.offer("c");
        //没有位置等待两秒
        //blockingQueue.offer("d",4, TimeUnit.SECONDS);
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        blockingQueue.poll(4,TimeUnit.SECONDS);
    }

SynchronousQueue同步队列

没有容量,进去一个元素,必须等取出来之后才能继续放元素

//同步队列
//和其他BlockingQueue不一样,SynchronousQueue不存储元素
//put一个元素就必须取出一个元素
public class SynchronousQueueDemo {
    public static void main(String[] args) {
        BlockingQueue blockingQueue = new SynchronousQueue<>();
        new Thread(()->{
            for (int i = 0; i < 3; i++) {
                try {
                    System.out.println(Thread.currentThread().getName()+" put "+i);
                    blockingQueue.put(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"T1").start();
        new Thread(()->{
            for (int i = 0; i < 3; i++) {
                try {
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName()+" take "+blockingQueue.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"T2").start();
    }
}

线程池

线程池:三大方法,七大参数,四种拒绝策略

池化技术

程序的运行会占用系统资源!就需要优化资源的使用!=> 池化技术

  • 线程池
  • 连接池
  • 内存池
  • 对象池

池化技术:解决因为资源的创建,销毁十分浪费时间的问题,事先准备一些资源,有需要就用,用完就还

线程池的好处

  1. 降低资源消耗
  2. 提高运行效率
  3. 方便管理(线程复用,控制最大并发数,管理线程)

三大方法

0

测试

//Executors工具类,三大方法
public class Demo01 {
    public static void main(String[] args) {
        //ExecutorService executorService = Executors.newSingleThreadExecutor();//单个线程
        //ExecutorService executorService = Executors.newFixedThreadPool(3);//创建一个固定大小的线程池
        ExecutorService executorService = Executors.newCachedThreadPool();//可以弹性变化的线程池
        try {
            for (int i = 0; i < 100; i++) {
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
        //线程池用完,一定要关闭
    }
}

源码分析

newSingleThreadExecutor

    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

newFixedThreadPool

    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

newCachedThreadPool

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,//约等于21亿,OOM内存溢出
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

本质(参数对应下面的七大参数)

    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;
    }

七大参数

int corePoolSize,//核心线程数
int maximumPoolSize,//最大核心线程池线程数量
long keepAliveTime,//超时没有调用就释放
TimeUnit unit,//超时单位
BlockingQueue<Runnable> workQueue,//阻塞队列
ThreadFactory threadFactory,//线程工厂,创建线程的,一般不动
RejectedExecutionHandler handler//拒绝策略

image-20200425121256805

image-20200425121454838

四种拒绝策略

image-20200425121944847

                //AbortPolicy 拒绝策略,并且抛出异常
                //CallerRunsPolicy 哪来的去哪里
                //DiscardPolicy 丢掉任务,不会抛出异常
                //DiscardOldestPolicy 尝试去和最早的竞争,竞争失败就失败,成功就执行

小结和拓展

了解:IO密集型,CPU密集型

        //最大线程到底该如何定义
        //1.CPU密集型 逻辑处理器数量,可以保持CPU的效率最高 Runtime.getRuntime().availableProcessors(),
        //2.IO密集型 一个程序,15个大型任务,IO十分占用资源 判断程序中十分耗IO的线程,一般X2
//Executors工具类,三大方法
public class Demo01 {
    public static void main(String[] args) {
        //ExecutorService executorService = Executors.newSingleThreadExecutor();//单个线程
        //ExecutorService executorService = Executors.newFixedThreadPool(3);//创建一个固定大小的线程池
        //ExecutorService executorService = Executors.newCachedThreadPool();//可以弹性变化的线程池
        //自定义线程池,工作中只会使用ThreadPoolExecutor
        ExecutorService executorService =new ThreadPoolExecutor(
                2,
                Runtime.getRuntime().availableProcessors(),
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
                //AbortPolicy 拒绝策略,并且抛出异常
                //CallerRunsPolicy 哪来的去哪里
                //DiscardPolicy 丢掉任务,不会抛出异常
                //DiscardOldestPolicy 尝试去和最早的竞争,竞争失败就失败,成功就执行
        );
        try {
            //最大队列=队列+max值
            //超出最大承载就会报错 比如main线程来的就交给main线程执行
            /*pool-1-thread-1ok
                    mainok
            pool-1-thread-2ok
            pool-1-thread-2ok*/
            for (int i = 0; i < 9; i++) {
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
        //线程池用完,一定要关闭
    }
}

四大函数式接口

lambdab表达式,链式编程,函数式接口,Stream流式计算

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

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}
//超级多FunctionalInterface
//简化编程模型,在新版本的框架底层大量应用
//foreach(消费者类型的函数式接口)

image-20200425130258552

Function

image-20200425130528344.

/*
* Function 函数型接口 有一个输入参数,有一个输出
* 只要是函数式接口,就可以用lambda表达式简化
Lambda表达式的省略模式
省略规则:
  ●参数类型可以省略。 但是有多个参数的情况下,不能只省略一个
  ●如果参数有且仅有一 个,那么小括号可以省略
  ●如果代码块的语句只有一 条,可以省略大括号和分号,甚至是return
* */
public class Demo1 {
    public static void main(String[] args) {
        /*Function function = new Function<String,String>() {
            @Override
            public String apply(String str) {
                return str;
            }
        };*/
        Function<String,String> function = str->str;
        System.out.println(function.apply("234564"));
    }
}

Predicate

image-20200425131513060.

/*
* 断定型接口:有一个输入参数,返回值只能是boolean值
* */
public class Demo02 {
    public static void main(String[] args) {
        //判断字符串是否为空
        /*Predicate<String> predicate = new Predicate<String>() {
            @Override
            public boolean test(String o) {
                return o.isEmpty();
            }
        };*/
        Predicate<String> predicate=str->str.isEmpty();
        System.out.println(predicate.test("456456"));
        System.out.println(predicate.test(""));
    }
        /*false
        true*/
}

Supplier

供给型接口

image-20200425132442246.

/*
* Supplier 供给型接口 没有参数 只有返回值
* */
public class Demo04 {
    public static void main(String[] args) {
        /*Supplier<String> supplier = new Supplier<String>() {
            @Override
            public String get() {
                return "ao li gei";
            }
        };*/
        Supplier<String> supplier=()->"ao li gei";
        System.out.println(supplier.get());
    }
}

Consumer

消费型接口

image-20200425132053218.

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

Stream流式计算

image-20200425133736223

  • User
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
    private int age;
}
  • Test
public class Test {
    public static void main(String[] args) {
        User user1 = new User(1, "a", 21);
        User user2 = new User(2, "b", 22);
        User user3 = new User(3, "c", 23);
        User user4 = new User(4, "d", 24);
        User user5 = new User(6, "e", 25);
        //集合就是存储
        List<User> users = Arrays.asList(user1, user2, user3, user4, user5);
        //流就是用来计算
        //找到id是偶数的
        //年龄必须大于23
        //用户名转换成大写
        //用户名名字倒着排序
        //只输出一个用户名
        users.stream()
                .filter(user -> user.getId()%2==0)
                .filter(user -> user.getAge()>23)
                .map(user -> user.getName().toUpperCase())
                .sorted((t1,t2)->t1.compareTo(t2))
                .limit(1)
                .forEach(System.out::println);
    }
}

ForkJoin

什么是ForkJoin?

ForkJoin是在JDK1.7出现的,并发执行任务,提高效率,大数据量

大数据:Map Reduce(把大任务拆分为小任务)

image-20200425140407223

ForkJoin特点:工作窃取(里面维护的都是双端队列,多线程同时执行,其中一部分线程先执行完,就会把其他线程未执行完的任务拿过来帮忙处理)

操作

image-20200425141659765

image-20200425141821434.

  • ForkJoinDemo
//求和计算任务
//如何使用ForkJoin,
// 1.通过forkjoinpool来执行
// 2.计算任务forkjoinpool.execute(ForkJoinTask)
// 3.你的计算类要继承RecursiveTask Recursive递归
public class ForkJoinDemo extends RecursiveTask<Long> {
    private Long start;
    private Long end;
    //临界值,超过就拆分
    private Long temp=10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }
    //计算方法
    @Override
    protected Long compute() {
        if ((end-start)<temp){
            long sum=0;
            for (long i = start; i <=end ; i++) {
                sum+=i;
            }
            return sum;
        }else {
            long middle=(start+end)/2;//中间值
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            ForkJoinDemo task2 = new ForkJoinDemo(middle+1, end);
            task1.fork();//拆分任务,把任务压入线程队列
            task2.fork();//拆分任务,把任务压入线程队列
            return task1.join() + task2.join();
        }
    }
}
  • Test
//3(循环) 6(ForkJoin) 9(并行流)等
public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1();
        test2();
        test3();
        /*sum=2000000001000000000,time=1976
        sum=2000000001000000000,time=2616
        sum=2000000001000000000,time=1219*/
    }
    //普通程序员
    public static void test1(){
        long start = System.currentTimeMillis();
        long sum=0;
        for (long i = 1; i <=20_0000_0000; i++) {
            sum+=i;
        }
        long end = System.currentTimeMillis();
        System.out.printf("sum=%d,time=%d\n",sum,end-start);
    }
    /*execute(ForkJoinTask) 异步执行tasks,无返回值
    invoke(ForkJoinTask) 有Join, tasks会被同步到主进程
    submit(ForkJoinTask) 异步执行,且带Task返回值,可通过task.get 实现同步到主线程*/
    //会用forkjoin的程序员
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        long sum=0;
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinDemo forkJoinDemo = new ForkJoinDemo(0L, 20_0000_0000L);
        sum=forkJoinPool.submit(forkJoinDemo).get();
        long end = System.currentTimeMillis();
        System.out.printf("sum=%d,time=%d\n",sum,end-start);
    }
    //牛逼程序员
    public static void test3(){
        long start = System.currentTimeMillis();
        long sum=0;
        //Stream并行流
        sum=LongStream.rangeClosed(0L,20_0000_0000L).parallel().reduce(0,Long::sum);
        long end = System.currentTimeMillis();
        System.out.printf("sum=%d,time=%d\n",sum,end-start);
    }
}

异步回调

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

image-20200425153618927

其中用到的一些方法和含义

//异步调用:CompletableFuture
//异步执行
//成功回调
//失败回调
public class Demo01 {
    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()+" is ok ");
        });
        System.out.println(111111);
         System.out.println(completableFuture.get()); //阻塞获取结果
        System.out.println(222222);*/
        //有返回值
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(()->{
            int sum=1/0;
            return "456465";
        });
        /*System.out.println(111111);
        System.out.println(completableFuture.get());
        System.out.println(222222);*/
        //如果发生异常,这样也会发生异常,就不太好
        System.out.println(completableFuture.whenComplete((t, u) -> {
            System.out.println("t==>" + t);//t代表正常返回结果
            System.out.println("u==>" + u);//错误信息 java.lang.ArithmeticException: / by zero
        }).exceptionally(e -> {
            System.out.println(e.getMessage()); //java.lang.ArithmeticException: / by zero
            return "2333"; //失败可以获取到错误的返回结果
        }).get());
    }
}

JMM

请你谈谈你对Volatile的理解

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

  1. 保证可见性
  2. 不保证原子性
  3. 禁止指令重排

什么是JMM

JMM:java内存模型,不存在的东西,是个概念,约定

关于JMM的一些同步的约定:

  1. 线程解锁前,必须把共享变量立即刷回主存
  2. 线程加锁前,必须读取主存中的最新值到工作内存中
  3. 加锁和解锁是同一把锁

八种操作(内存交互操作)

image-20200425164127994

image-20200425164316377

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

问题:程序不知道内存的值已经被修改过来,向下看

Volatile

保证可见性

public class JMMTest {
    //不加volatile程序就会死循环
    //加了volatile可以保证程序的可见性
    private volatile static int number=0;
    public static void main(String[] args) {//main线程
        new Thread(()->{ //线程1
            while (number==0){

            }
        }).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        number=1;
        System.out.println(number);
    }
}

不保证原子性

原子性:不可分割

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

//不保证原子性
public class Demo02 {
    private volatile static int num=0;
    public  static void add(){
        num++;
    }
    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 1000; i1++) {
                    add();
                }
            }).start();
        }
        //理论结果应该为20000
        //第一次实际是 19291
        while (Thread.activeCount()>2){
            Thread.yield();//线程礼让
        }
        System.out.println(Thread.currentThread().getName()+" "+num);
    }
}

如果不加synchronized和lock如何保证原子性?

image-20200425170757155

  1. 使用原子类解决原子性问题

image-20200425170857971.

//保证原子性
public class Demo02 {
    private static AtomicInteger num=new AtomicInteger();
    public  static void add(){
        num.getAndIncrement();//AtomicInteger+1方法,CAS
    }
    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 1000; i1++) {
                    add();
                }
            }).start();
        }
        //理论结果应该为20000
        //第一次实际是 19291
        while (Thread.activeCount()>2){
            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

可能造成的结果: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指令。作用:

  1. 保证特定的操作执行顺序
  2. 可以保证某些遍历的内存可见性(利用这些特性,就可以保证volatile实现了可见性)

image-20200425175305569.

单例模式

饿汉式,DCL懒汉式

饿汉式

//饿汉式单例
public class Hungry {
    //可能会浪费时间,因此就需要用到懒汉式
    private byte[] data=new byte[1024*1024];
    private Hungry(){}
    private final static Hungry hungry=new Hungry();
    public static Hungry getInstance(){
        return hungry;
    }
}

DCL懒汉式

//懒汉式单例
public class LazyMan {
    private LazyMan(){
        System.out.println(Thread.currentThread().getName()+" is ok");
    }
    private volatile static LazyMan lazyMan;
    //双重检测锁模式的懒汉式单例,简称DCL懒汉式
    public  static LazyMan getInstance(){
        if (lazyMan==null){
            synchronized (LazyMan.class){
                if (lazyMan==null){
                    lazyMan=new LazyMan();//不是原子性操作
                }
            }
        }
        return lazyMan;
    }
    //单线程下单例没问题,并发下就可能出现问题
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                LazyMan.getInstance();
            }).start();
        }
    }
    /*
     * 1.分配内存空间
     * 2.执行构造方法,初始化对象
     * 3.会把对象指向这个空间
     *
     * 期望执行 1 2 3
     * 实际执行 1 3 2就会在对象还未初始化之前暂时占据内存空间
     * 当另外一条线程来拿这个对象的时候,就会以为这个已经有了,实际上并没有
     * 解决办法:加上volatile
     * */
}

花里胡哨且没用的静态内部类

//静态内部类
public class Holder {
    private Holder(){}
    public static Holder getInstance(){
        return InnerClass.holder;
    }
    public static class InnerClass{
        private static final Holder holder=new Holder();
    }
}

单例不安全,因为有反射

枚举

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);
    }
}

image-20200425183916855

最终章枚举单例

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);
    }
}

深入理解CAS

什么是CAS

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

缺点:

  1. 底层是自旋锁,循环会耗时
  2. 一次性只能保证一个共享变量的原子性
  3. 存在ABA问题
public class CASDemo {
    //CAS compareAndSet比较并交换
    public static void main(String[] args) {
        AtomicInteger atomicInteger=new AtomicInteger(2020);
        //期望,更新
        //public final boolean compareAndSet(int expect, int update)
        //如果我期望的值达到了就更新,否则就不更新 CAS是cpu的并发原语
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());
        /*true
        2021
        false
        2021*/
    }
}

Unsafe

image-20200425190723610

image-20200425191441271

image-20200425191546452

ABA问题(狸猫换太子)

什么是ABA问题?

image-20200425200149986

public class CASDemo {
    //CAS compareAndSet比较并交换
    public static void main(String[] args) {
        AtomicInteger atomicInteger=new AtomicInteger(2020);
        //期望,更新
        //public final boolean compareAndSet(int expect, int update)
        //如果我期望的值达到了就更新,否则就不更新 CAS是cpu的并发原语
        System.out.println("==========捣蛋线程========");
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(2021, 2020));
        System.out.println(atomicInteger.get());
        System.out.println("==========捣蛋线程========");
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());
        /*true
        2021
        false
        2021*/
    }
}

如何解决?看下面的原子引用

原子引用

解决ABA问题,引入原子引用,对应的思想就是乐观锁

image-20200425200818944.

image-20200425202620117

public class CASDemo {
    //CAS compareAndSet比较并交换
    //AtomicStampedReference注意:如果泛型是包装类,要注意引用问题
    public static void main(String[] args) {
        //正常业务,这里面一般都是一个个对象
        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(1, 1);
        new Thread(()->{
            System.out.println("a 1 " +atomicStampedReference.getStamp());
            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("a 2 " +atomicStampedReference.getStamp());
            System.out.println(atomicStampedReference.compareAndSet(2, 1, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
            System.out.println("a 3 " +atomicStampedReference.getStamp());
        },"A").start();
        //乐观锁原理相同
        new Thread(()->{
            int stamp = atomicStampedReference.getStamp();//获得版本号
            System.out.println("b 1 " +stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(atomicStampedReference.compareAndSet(1, 2, stamp, stamp + 1));
            System.out.println("b 1 "+atomicStampedReference.getStamp());
        },"B").start();
    }
}

各种锁的理解

公平锁、非公平锁

公平锁:需要排队,必须先来后到

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

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

可重入锁(递归锁)

拿到锁之后还可以获得锁,而不会死锁

image-20200425204733052

synchronized

package com.antake.lock;

import java.util.concurrent.*;

/**
 * @author Antake
 */
public class Demo01 {
    public static void main(String[] args) {
        Phone phone=new Phone();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());
        for (int i = 0; i < 2; i++) {
            threadPoolExecutor.execute(phone::sms);
        }
        threadPoolExecutor.shutdown();
    }
}
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.antake.lock;

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

/**
 * @author Antake
 */
public class Demo02 {
    public static void main(String[] args) {
        Phone2 phone=new Phone2();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(100), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());
        for (int i = 0; i < 2; i++) {
            threadPoolExecutor.execute(phone::sms);
        }
        threadPoolExecutor.shutdown();
    }
}
class Phone2{
    private final Lock lock=new ReentrantLock();
    public synchronized void sms(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" sms");
            //这里也有锁
            call();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public synchronized void call(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" call");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

自旋锁 spinlock

image-20200425213037170

自定义自旋锁

package com.antake.lock;

/**
 * @author Antake
 * @date 2020/4/25
 */

import java.util.concurrent.atomic.AtomicReference;

/**
* 自旋锁
*/
public class SpinlockDemo {
    AtomicReference<Thread> atomicReference=new AtomicReference<>();
    /**
    * @Description: 加锁
    * @Param: []
    * @return: void
    * @Author: MiZiMi
    * @Date: 2020/4/25 21:36
    */
    public void myLock(){
        Thread thread=Thread.currentThread();
        System.out.println(thread.getName()+"==> myLock");
        while (!atomicReference.compareAndSet(null,thread)){

        }
    }
    /**
    * @Description: 解锁
    * @Param: []
    * @return: void
    * @Author: MiZiMi
    * @Date: 2020/4/25 21:37
    */
    public void myUnlock(){
        Thread thread=Thread.currentThread();
        System.out.println(thread.getName()+"==> unLock");
        atomicReference.compareAndSet(thread,null);
    }
}

测试

package com.antake.lock;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Antake
 * @date 2020/4/25
 */
public class TestSpinlock {
    public static void main(String[] args) {
        //底层使用的自旋锁CAS
        SpinlockDemo spinlockDemo = new SpinlockDemo();
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 2, 0,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());
        try {
            poolExecutor.execute(()->{
                spinlockDemo.myLock();
                try {
                    TimeUnit.SECONDS.sleep(3);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    spinlockDemo.myUnlock();
                }
            });
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            poolExecutor.execute(()->{
                spinlockDemo.myLock();
                try {
                    TimeUnit.SECONDS.sleep(3);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    spinlockDemo.myUnlock();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            poolExecutor.shutdown();
        }
    }
}

死锁

什么是死锁

互相争夺资源

image-20200425214935106

死锁产生的四个必要条件

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

怎么排除死锁?

  1. 使用jsp -l定位进行号

image-20200425215804651

  1. 使用jstack 进程号找到死锁问题

image-20200425215955635

面试,工作中!排查问题:

  1. 日志
  2. 堆栈

未解决-分布式死锁

posted @ 2020-04-25 22:14  Antake  阅读(178)  评论(0)    收藏  举报
Live2D