JUC学习记录

JUC学习记录

小狂神学习笔记

JUC学习第二天

Callable的使用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uKopi78n-1650457646491)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650438205923.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-T2PC38Tu-1650457646492)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650437908870.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IPB4yNqV-1650457646492)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650438195301.png)]

package com.xuda.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 14:55
 */
public class CallableTest {
    //如何启动Callabel
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyThread thread = new MyThread();
        FutureTask futureTask = new FutureTask(thread);
        new Thread(futureTask,"A").start();
        new Thread(futureTask,"B").start();
        Integer o = (Integer) futureTask.get(); //可能会产生阻塞
        //异步通信执行
        System.out.println(o);
    }
}
class MyThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println("call()");
        return 1024;
    }
}

常用的辅助类

countDownLatch

计数器

package com.xuda.callable;

import java.util.concurrent.CountDownLatch;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 15:04
 */
//计数器
public class CountDownLatchTest {
    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)).start();
        }
        countDownLatch.await(); //等待计时器归零,然后再向下执行
        System.out.println("close door");
    }
}

原理: countDownLatch.countDown(); // 数量-1

countDownLatch.await();

/等待计数器归零,然后再向下执行 每次有线程调用 countDown() 数量-1,假设计数器变为0,

countDownLatch.await() 就会被唤醒,继续 执行!

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oAlNG4H1-1650457646492)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650438587497.png)]

CyclicBarrier

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tIL6s8B9-1650457646493)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650438959384.png)]

package com.xuda.callable;

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

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 15:15
 */
//加法计数器
public class CyclicBarrierTest {
    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+"珂");
                try {
                    cyclicBarrier.await(); //等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-s76WyD1G-1650457646493)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650439159854.png)]

Semaphore 信号量

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mrHSrJ7G-1650457646494)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650439200075.png)]

package com.xuda.callable;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 15:19
 */
//抢车位
public class SemaphoreTest {
    public static void main(String[] args) throws InterruptedException {
        //线程数量:停车位 限流
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "抢到车位");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName()+"离开车位");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release(); //释放
                }
                  },String.valueOf(i)).start();
    }
    }
}

原理: semaphore.acquire() 获得,假设如果已经满了,等待,等待被释放为止!

semaphore.release(); 释放,会将当前的信号量释放 + 1,然后唤醒等待的线程! 作用: 多个共享资源互斥的使用!并发限流,控制最大的线程数!

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TIN0tST9-1650457646495)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650439469206.png)]

读写 锁

ReadWriteLock

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IUujkhow-1650457646495)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650440279760.png)]

ReadWriteLock

package com.xuda.rwlock;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 15:38
 */

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

/**
 * 独占锁(写锁) 一次只能被一个线程占有
 * 共享锁(读锁) 多个线程可以同时占有
 * ReadWriteLock
 * 读-读 可以共存!
 * 读-写 不能共存!
 * 写-写 不能共存!
 */

public class ReadWriteLockTest {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        //写入
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.put(temp + "", temp + "");
            }, String.valueOf(i)).start();
        }
        //读取
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.get(temp + "");
            }, String.valueOf(i)).start();
        }
        MyCacheLock myCacheLock = new MyCacheLock();
        //写入
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCacheLock.put(temp + "", temp + "");
            }, String.valueOf(i)).start();
        }
        //读取
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCacheLock.get(temp + "");
            }, String.valueOf(i)).start();
        }
    }
}
//加锁
//volatile :防止程序编译对代码优化
class MyCacheLock {
    private volatile Map<String,Object> map = new HashMap<>();
    //读写锁 更加细粒度的控制
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private Lock lock = new ReentrantLock();
    //存,写入的时候,只希望同时有一个线程写
    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");
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3F9PWUxW-1650457646496)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650441993642.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9TQOCGyL-1650457646497)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650442137439.png)]

阻塞队列

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9l6v2Ft0-1650457646498)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650442199526.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VHNoXGhn-1650457646498)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650442210193.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TEqhncEV-1650457646499)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650442230609.png)]

BlockingQueue

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DG2ejF5N-1650457646499)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650442244631.png)]

什么情况下我们会使用 阻塞队列:多线程并发处理,线程池! 学会使用队列 添加、移除 四组API

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LPB13bpa-1650457646499)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650442290734.png)]

package com.xuda.queue;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 16:12
 */
/**
* 抛出异常
*/
public class test1 {
    public static void main(String[] args) {
        //队列大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("b"));
        System.out.println(blockingQueue.add("c"));
// IllegalStateException: Queue full 抛出异常!
// System.out.println(blockingQueue.add("d"));

        System.out.println("========");
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        // java.util.NoSuchElementException 抛出异常!
// System.out.println(blockingQueue.remove());
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NwWbcUJI-1650457646500)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650442515196.png)]

package com.xuda.queue;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 16:12
 */
/**
* 有返回值,没有异常
*/
public class test1 {
    public static void main(String[] args) {
        //队列大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));
// false 不抛出异常!
// System.out.println(blockingQueue.offer("d"));

        System.out.println("========");
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
// System.out.println(blockingQueue.poll()); null 不抛出异常
        
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wcIwTKRk-1650457646500)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650442640660.png)]

package com.xuda.queue;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 16:12
 */
/**
* 等待,阻塞(等待超时)
*/
public class test1 {
    public static void main(String[] args) throws InterruptedException {
        //队列大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));
        blockingQueue.offer("d", 2,TimeUnit.SECONDS);

        System.out.println("========");
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        blockingQueue.poll(2,TimeUnit.SECONDS);// 两秒后退出

    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LC9hgGfK-1650457646500)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650442775579.png)]

SynchronousQueue 同步队列

没有容量, 进去一个元素,必须等待取出来之后,才能再往里面放一个元素! put、take

package com.xuda.queue;

import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 16:28
 */
public class synQueue {
    public static void main(String[] args) {
        BlockingQueue<String> blockingqueue = new SynchronousQueue<>(); //同步队列
        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName()+"put 1");
                blockingqueue.put("1");
                System.out.println(Thread.currentThread().getName()+"put 2");
                blockingqueue.put("2");
                System.out.println(Thread.currentThread().getName()+"put 3");
                blockingqueue.put("3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T1").start();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+"=>"+blockingqueue.take());
                TimeUnit.SECONDS.sleep(2);
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+"=>"+blockingqueue.take());
                TimeUnit.SECONDS.sleep(2);
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+"=>"+blockingqueue.take());
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T2").start();
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dRjT0wdC-1650457646501)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650443695617.png)]

线程池

线程池:三大方法、7大参数、4种拒绝策略

池化技术 程序的运行,本质:占用系统的资源! 优化资源的使用!=>池化技术

线程池、连接池、内存池、对象池///… 创建、销毁。十分浪费资源

池化技术:事先准备好一些资源,有人要用,就来我这里拿,用完之后还给我。

线程池的好处:

1、降低资源的消耗

2、提高响应的速度

3、方便管理。

线程复用、可以控制最大并发数、管理线程

线程池:三大方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-O6KKmekH-1650457646501)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650443778434.png)]

package com.xuda.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 16:36
 */
public class PoolTest1 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();//单个线程
        // ExecutorService threadPool = Executors.newFixedThreadPool(5); // 创建一
    //    个固定的线程池的大小
// ExecutorService threadPool = Executors.newCachedThreadPool(); // 可伸缩
     //   的,会指定增加,
        try {
            for (int i = 0; i < 20; i++) {
                executorService.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "OK");
                });
            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            //线程使用完,程序结束 关闭线程池
            executorService.shutdown();
        }
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XoSR4H1a-1650457646501)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650444564290.png)]

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(5, 5,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
// 本质ThreadPoolExecutor()
public ThreadPoolExecutor(int corePoolSize, // 核心线程池大小
	int maximumPoolSize, // 最大核心线程池大小
	long keepAliveTime, // 超时了没有人调用就会释放
	TimeUnit unit, // 超时单位
	BlockingQueue<Runnable> workQueue, // 阻塞队列
	ThreadFactory threadFactory, // 线程工厂:创建线程的,一般
不用动
	RejectedExecutionHandler handle // 拒绝策略) {
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;
}

在这里插入图片描述

手动创建一个线程

package com.xuda.threadpool;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 16:52
 */
// Executors 工具类、3大方法

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

/**
 * new ThreadPoolExecutor.AbortPolicy() // 银行满了,还有人进来,不处理这个人的,抛出异
 常
 * new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里!
 * new ThreadPoolExecutor.DiscardPolicy() //队列满了,丢掉任务,不会抛出异常!
 * new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了,尝试去和最早的竞争,也不会
 抛出异常!
 */
public class poolex {
    public static void main(String[] args) {
        //自定义线程池 工作
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                5,
                 3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()); //队列满了,尝试去和最早的竞争,也不会抛出异常
            try {
                //最大承载: Deque + max
                //超过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();
            }
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-r7v8Swgf-1650457646502)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650445159447.png)]

4.种拒绝策略

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QJItq06s-1650457646502)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650445183609.png)]

扩展

池的最大的大小如何去设置!

了解:IO密集型,CPU密集型:(调优)

package com.xuda.threadpool;

import java.util.concurrent.*;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 17:01
 */
public class BestPoolThread {
    public static void main(String[] args) {
        // 自定义线程池!工作 ThreadPoolExecutor
        // 最大线程到底该如何定义
        // 1、CPU 密集型,几核,就是几,可以保持CPu的效率最高!
        // 2、IO 密集型 > 判断你程序中十分耗IO的线程,
        // 程序 15个大型任务 io十分占用资源!
        // 获取CPU的核数
        System.out.println(Runtime.getRuntime().availableProcessors());

        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                Runtime.getRuntime().availableProcessors(),
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        try {
// 最大承载:Deque + max
// 超过 RejectedExecutionException
            for (int i = 1; i <= 9; i++) {
// 使用了线程池之后,使用线程池来创建线程
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
// 线程池用完,程序结束,关闭线程池
            threadPool.shutdown();
        }
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ea2tjA01-1650457646503)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650445452441.png)]

四大函数式接口

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

函数式接口: 只有一个方法的接口
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
// 泛型、枚举、反射
// lambda表达式、链式编程、函数式接口、Stream流式计算
// 超级多FunctionalInterface
// 简化编程模型,在新版本的框架底层大量应用!
// foreach(消费者类的函数式接口)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lUh1BWoY-1650457646503)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650445543352.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7v0ok9w3-1650457646503)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650445553316.png)]

import java.util.function.Function;
/**
* Function 函数型接口, 有一个输入参数,有一个输出
* 只要是 函数型接口 可以 用 lambda表达式简化
*/
public class Demo01 {
	public static void main(String[] args) {
//
// Function<String,String> function = new Function<String,String>() {
// @Override
// 	public String apply(String str) {
// 			return str;
    // }
// 		};
			Function<String,String> function = (str)->{return str;};
			System.out.println(function.apply("asd"));
	}
}

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EVey7D1f-1650457646505)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650445622606.png)]

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

Consumer 消费型接口

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-G55T11I7-1650457646505)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650445667587.png)]

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

Supplier 供给型接口

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-71p5y1gF-1650457646505)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650445707828.png)]

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

Stream流式计算

什么是Stream流式计算

大数据:存储 + 计算 集合、MySQL 本质就是存储东西的; 计算都应该交给流来操作! [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-b9hnjqx4-1650457646505)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650445788949.png)]

package com.xuda.streamdemo;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 17:13
 */

import java.util.Arrays;
import java.util.List;

/**
 * 题目要求:一分钟内完成此题,只能用一行代码实现!
 * 现在有5个用户!筛选:
 * 1、ID 必须是偶数
 * 2、年龄必须大于23岁
 * 3、用户名转为大写字母
 * 4、用户名字母倒着排序
 * 5、只输出一个用户!
 */
public class StreamTest {
    public static void main(String[] args) {
        User u1 = new User(1,"a",21);
        User u2 = new User(2,"b",22);
        User u3 = new User(3,"c",23);
        User u4 = new User(4,"d",24);
        User u5 = new User(5,"e",25);
        //集合就是存储
        List<User> users = Arrays.asList(u1, u2, u3, u4, u5);
        //计算交给Stream流
        users.stream()
                .filter(u->{return u.getId()%2==0;})
                .filter(u->{return u.getAge()>23;})
                .map(u->{return u.getUsername().toUpperCase();})
                .sorted((uu1,uu2)->{return uu2.compareTo(uu1);})
                .limit(1)
                .forEach(System.out::println);
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yu4ZG2EY-1650457646505)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650446448147.png)]

ForkJoin

什么是 ForkJoin

ForkJoin 在 JDK 1.7 , 并行执行任务!提高效率。大数据量! 大数据:Map Reduce (把大任务拆分为小任务)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ayGr9Cjd-1650457646505)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650446495951.png)]

ForkJoin 特点:工作窃取

这个里面维护的都是双端队列
在这里插入图片描述

package com.xuda.streamdemo;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 17:33
 */
public class ForkJoinTestDemoo {
    public static void main(String[] args) throws ExecutionException,
            InterruptedException {
// test1(); // 12224
// test2(); // 10038
// test3(); // 153
    }
    // 普通程序员
    public static void test1(){
        Long sum = 0L;
        long start = System.currentTimeMillis();
        for (Long i = 1L; i <= 10_0000_0000; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+" 时间:"+(end-start));
    }
    // 会使用ForkJoin
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinTest(0L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);// 提交任务
        Long sum = submit.get();
        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+" 时间:"+(end-start));
    }
    public static void test3(){
        long start = System.currentTimeMillis();
    // Stream并行流 ()
        long sum = LongStream.rangeClosed(0L,
                10_0000_0000L).parallel().reduce(0, Long::sum);
        long end = System.currentTimeMillis();

        System.out.println("sum="+"时间:"+(end-start));
    }
}


package com.xuda.streamdemo;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 17:23
 */

import java.util.concurrent.RecursiveTask;

/**
 * 求和计算的任务!
 * 3000 6000(ForkJoin) 9000(Stream并行流)
 * // 如何使用 forkjoin
 * // 1、forkjoinPool 通过它来执行
 * // 2、计算任务 forkjoinPool.execute(ForkJoinTask task)
 * // 3. 计算类要继承 ForkJoinTask
 */

public class ForkJoinTest extends RecursiveTask<Long> {
    private Long start;//1
    private Long end;
    //临界值
    private Long temp = 10000L;

    public ForkJoinTest(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if ((end - start) < temp) {
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            //forkjoin 递归
            long middle = (start - end) / 2; //中间值
            ForkJoinTest test1 = new ForkJoinTest(start, middle);
            test1.fork(); //拆分任务 ,把任务压入线程队列
            ForkJoinTest test2 = new ForkJoinTest(middle + 1, end);
            test2.fork(); // 拆分任务,把任务压入线程队列
            return test1.join() + test2.join();
        }
        //计算方法

    }
}

异步回调

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6l2PNy0J-1650457646507)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650447445705.png)]

package com.xuda.future;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 17:38
 */

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

import static sun.plugin.util.ProgressMonitor.get;

/**
 * 异步调用: CompletableFuture
 * // 异步执行
 * // 成功回调
 * // 失败回调
 */

public class FutureTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //没有返回值的renasync异步调用
       // 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("1111");
//
//      completableFuture.get(); // 获取阻塞执行结果
//      有返回值的 supplyAsync 异步回调
//      ajax,成功和失败的回调
        // 返回的是错误信息;

        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(()->{
            System.out.println(Thread.currentThread().getName()+"supplyasync=>integer");
            int i = 10/0;
            return 1024;
        });
        System.out.println(completableFuture.whenComplete((t, u) -> {
            System.out.println("t=>" + t); // 正常的返回结果
            System.out.println("u=>" + u); // 错误信息:
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 233; // 可以获取到错误的返回结果
        }).get());
/**
 * succee Code 200
 * error Code 404 500
 */
    }
}

jvm

请你谈谈你对 Volatile 的理解

Volatile 是 Java 虚拟机提供轻量级的同步机制 1、保证可见性 2、不保证原子性 3、禁止指令重排

什么是JMM

JMM : Java内存模型,不存在的东西,概念!约定!

关于JMM的一些同步的约定: 1、线程解锁前,必须把共享变量立刻刷回主存。 2、线程加锁前,必须读取主存中的最新值到工作内存中!

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

线程 工作内存 、主内存

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wHd584Df-1650457646509)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650451604048.png)]

内存交互操作有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操作之前,必须把此变量同步回主内存 问题: 程序不知道主内存的值已经被修改过了

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VooraRdq-1650457646508)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650451124294.png)]

Volatile

1.保持可见性

package com.xuda.jvm;

import java.util.concurrent.TimeUnit;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 18:39
 */
public class jmmTEst {
    private volatile static int num = 0;
    public static void main(String[] args) {
        new Thread(()->{
           while (num == 0) {

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

2.不保证原子性

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

package com.xuda.jvm;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 18:42
 */
public class VTest {
    // volatile 不保证原子性
    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 j = 0; j < 100; j++) {
                        add();
                    }
                }).start();
            }
            while (Thread.activeCount()>2) {
                Thread.yield();
            }
        System.out.println(Thread.currentThread().getName()+ " "+ num);
    }
}

如果不加 lock 和 synchronized ,怎么样保证原子性

用原子类,解决 原子性问题

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-exklK7k7-1650457646509)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650451655780.png)]

package com.xuda.jvm;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 18:48
 */
public class VDTest2 {
    // volatile 不保证原子性
    private volatile static AtomicInteger num = new AtomicInteger();
    public static void add() {
        // num ++ 不是一个原子操作
        num.getAndIncrement(); //cas
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int j = 0; j < 100; j++) {
                    add();
                }
            }).start();
        }
        while (Thread.activeCount() > 2) {
            //gc
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName()+ ""+num);
    }
}

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

指令重排 (volatile)

什么是 指令重排:

你写的程序,计算机并不是按照你写的那样去执行的。 源代码–>编译器优化的重排–> 指令并行也可能会重排–> 内存系统也会重排—> 执行 处理器在进行指令重排的时候,考虑:数据之间的依赖性!

volatile可以避免指令重排:

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

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

2、可以保证某些变量的内存可见性 (利用这些特性volatile实现了可见性)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-G0jX12sw-1650457646509)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650452224546.png)]

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

彻底玩转单例模式

饿汉式 DCL懒汉式,深究!

饿汉式
package com.xuda.jvm;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 18:58
 */
//饿汉单例
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;
    }
}

DCL懒汉式
package com.xuda.jvm;

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

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 19:00
 */
//DCL懒汉式
public class LazyMan {
    private static boolean qinjiang = false;
    private LazyMan(){
        synchronized (LazyMan.class){
            if (qinjiang == false){
                qinjiang = true;
            }else {
                throw new RuntimeException("不要试图使用反射破坏异常");
            }
}
}
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) throws Exception {
// LazyMan instance = LazyMan.getInstance();
        Field qinjiang = LazyMan.class.getDeclaredField("qinjiang");
        qinjiang.setAccessible(true);
        Constructor<LazyMan> declaredConstructor =
        LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        LazyMan instance = declaredConstructor.newInstance();
        qinjiang.set(instance,false);
        LazyMan instance2 = declaredConstructor.newInstance();
        System.out.println(instance);
        System.out.println(instance2);
    }
}
/**
 * 1. 分配内存空间
 * 2、执行构造方法,初始化对象
 * 3、把这个对象指向这个空间
 *
 * 123
 * 132 A
 * B // 此时lazyMan还没有完成构造
 */
枚举NUM
package com.xuda.jvm;

import com.sun.org.apache.bcel.internal.classfile.InnerClass;

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

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 19:05
 */
//enum 本身也是一个Class类
public enum  EnumSingle {
    INSTANCE;
    public EnumSingle getInstance() {
        return INSTANCE;
    }
}
class Test {

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        EnumSingle instance1 = EnumSingle.INSTANCE;
        Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class, int.class);
        declaredConstructor.setAccessible(true);
        EnumSingle enumSingle2 = declaredConstructor.newInstance();
        System.out.println(instance1);
        System.out.println(enumSingle2);
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uz7qF69G-1650457646510)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650453868196.png)]

枚举类型的最终反编译源码:

// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: EnumSingle.java
package com.kuang.single;

public final class EnumSingle extends Enum
{
    public static EnumSingle[] values()
    {
        return (EnumSingle[])$VALUES.clone();
    }
    public static EnumSingle valueOf(String name)
    {
        return (EnumSingle)Enum.valueOf(com/kuang/single/EnumSingle, name);
    }
    private EnumSingle(String s, int i)
    {
        super(s, i);
    }
    public EnumSingle getInstance()
    {
        return INSTANCE;
    }
    public static final EnumSingle INSTANCE;
    private static final EnumSingle $VALUES[];
    static
    {
        INSTANCE = new EnumSingle("INSTANCE", 0);
        $VALUES = (new EnumSingle[] {
            INSTANCE
        });
    }
}

理解CAS

 compareAndSet : 比较并交换!
package com.xuda.cas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 19:26
 */
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());

        atomicInteger.getAndIncrement();
        System.out.println(atomicInteger.compareAndSet(2020,2021));
        System.out.println(atomicInteger.get());
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-voF2uzSm-1650457646510)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650454118429.png)]

Unsafe 类
在这里插入图片描述

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

缺点: 1、 循环会耗时 2、一次性只能保证一个共享变量的原子性

3、ABA问题

CAS : ABA 问题(换取结果)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9nStjVGf-1650457646511)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650454963525.png)]

package com.xuda.cas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 19:42
 */
public class casTest {
    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(2021,2020));
        System.out.println(atomicInteger.get());

        //期望线程
        System.out.println(atomicInteger.compareAndSet(2020,2023));
        System.out.println(atomicInteger.get());

    }
}

原子引用

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

带版本号的操作

package com.xuda.cas;

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

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 19:46
 */
public class casTest1 {
    //AtomicStampedReference 注意,如果泛型是一个包装类,注意对象的引用问题
// 正常在业务操作,这里面比较的都是一个个对象
   static AtomicStampedReference atomicStampedReference = new AtomicStampedReference<>(1,1);

    public static void main(String[] args) {
        new Thread(()->{
            int temp = atomicStampedReference.getStamp(); //获取版本号
            System.out.println("a1=>"+temp);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicStampedReference.compareAndSet(1,2,atomicStampedReference.getStamp(),atomicStampedReference.getStamp() + 1);
            System.out.println("a2=>"+atomicStampedReference.getStamp());
            atomicStampedReference.compareAndSet(2,1,atomicStampedReference.getStamp(),atomicStampedReference.getStamp() + 1);
            System.out.println("a3=>"+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,stamp,stamp-1));
            System.out.println("b2"+atomicStampedReference.getStamp());
        },"b").start();
    }
}

在这里插入图片描述

各种锁的理解

1.公平锁 、非公平锁

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

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-W2QI2LAp-1650457646513)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650456361996.png)]

2.可重入锁

可重入锁(递归锁)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9jOKe4uI-1650457646513)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650456388282.png)]

Synchronized

package com.xuda;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 20:06
 */
//synchronizded
public class reLock {
    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(()->{
            phone.sms();
        }).start();
        new Thread(()->{
            phone.call();
        }).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");
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6HA55WbP-1650457646513)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650456574777.png)]

LOCK版

package com.xuda.lock;

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

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 20:10
 */
//LOCK
public class reLock {
    public static void main(String[] args) {
       Phone phone = new Phone();
        new Thread(()->{
            phone.sms();
        },"A").start();
        new Thread(()->{
            phone.call();
        },"B").start();
    }
}
class Phone {
    Lock lock =  new ReentrantLock();
    public  void sms() {
        lock.lock(); // 细节:lock.lock() 与lock.unlock();必须匹配否则就是死锁
        try {
            System.out.println(Thread.currentThread().getName() + "sms");
            call(); //加上锁
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
    public  void call() {
            lock.lock(); // 细节:lock.lock() 与lock.unlock();必须匹配否则就是死锁
            try {
                System.out.println(Thread.currentThread().getName() + "call");
            }catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xQPLTw6J-1650457646513)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650456881967.png)]

3.自旋锁

spinklock

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bTrg1nmH-1650457646513)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650456905885.png)]

package com.xuda.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 20:15
 */
//自旋锁
public class respin {

   AtomicReference<Thread> atomicReference = new AtomicReference<>();
   //加锁
    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.xuda.lock;

import java.util.concurrent.TimeUnit;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 20:19
 */
public class reTest {
    public static void main(String[] args) throws InterruptedException {
// ReentrantLock reentrantLock = new ReentrantLock();
// reentrantLock.lock();
// reentrantLock.unlock();
// 底层使用的自旋锁CAS
        respin lock = new respin();
        new Thread(()-> {
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myUnLock();
            }
        },"T1").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()-> {
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myUnLock();
            }
        },"T2").start();
    }

}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5HwpbrBg-1650457646514)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650457217221.png)]

死锁

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JRf3GFne-1650457646515)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650457238068.png)]

死锁测试,怎么排除死锁:

package com.xuda.rwlock;

import java.util.concurrent.TimeUnit;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-20 20:21
 */
public class DieLock {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(new MyThread(lockA,lockB),"T1").start();
        new Thread(new MyThread(lockB,lockA),"T1").start();
    }
}
class MyThread implements Runnable{
    private String lockA;
    private String lockB;

    public MyThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName()+"lock"+lockA+"==>get"+lockB);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName()+lockB+"lock"+"=>get"+lockA);
            }

        }
        
    }
}

解决问题

使用 jps -l 定位进程号

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bQLMn3Of-1650457646515)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650457595192.png)]

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aSciAlf4-1650457646515)(C:\Users\86176\AppData\Roaming\Typora\typora-user-images\1650457583911.png)]

面试,工作中! 排查问题: 1、日志 9 2、堆栈 1

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小徐同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值