1、什么是JUC

源码+官方文档 面试高频!

java.util工具包、包、分类

业务:普通的线程代码 Thread

Runnable 没有返回值,效率相比于Callable相对较低!

2、线程和进程

进程:一个程序,QQ.exe Music.exe 程序的集合;

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

java默认有几个线程?2个 main、GC

线程:开了一个进程Typora,写字,自动保存(线程负责的)

Thread、Runnable、Calleable

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

  1. public synchronized void start() {
  2. /**
  3. * This method is not invoked for the main method thread or "system"
  4. * group threads created/set up by the VM. Any new functionality added
  5. * to this method in the future may have to also be added to the VM.
  6. *
  7. * A zero status value corresponds to state "NEW".
  8. */
  9. if (threadStatus != 0)
  10. throw new IllegalThreadStateException();
  11. /* Notify the group that this thread is about to be started
  12. * so that it can be added to the group's list of threads
  13. * and the group's unstarted count can be decremented. */
  14. group.add(this);
  15. boolean started = false;
  16. try {
  17. start0();
  18. started = true;
  19. } finally {
  20. try {
  21. if (!started) {
  22. group.threadStartFailed(this);
  23. }
  24. } catch (Throwable ignore) {
  25. /* do nothing. If start0 threw a Throwable then
  26. it will be passed up the call stack */
  27. }
  28. }
  29. }
  30. //本地方法,调用底层的c++,java无法直接操作硬件
  31. private native void start0();

并发,并行

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

  • CPU一核,模拟出来多条线程,快速交替

并行(多个人一起行走)

  • CPU多核,多个线程可以同时执行;线程池
  1. package com.cyx.demo01;
  2. public class test1 {
  3. public static void main(String[] args) {
  4. //获取cpu的核数
  5. //cpu密集型,IO密集型
  6. System.out.println(Runtime.getRuntime().availableProcessors());
  7. }
  8. }

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

线程有几个状态

  1. public enum State {
  2. //新生
  3. NEW,
  4. //运行
  5. RUNNABLE,
  6. //阻塞
  7. BLOCKED,
  8. //等待,死死的等
  9. WAITING,
  10. //超时等待
  11. TIMED_WAITING,
  12. //终止
  13. TERMINATED;
  14. }

wait/sleep区别

  1. 来自不同的类
    wait => Object
    sleep => Thread
  2. 关于锁的释放
    wait会释放锁,sleep睡觉了,抱着锁睡觉,不会释放
  3. 使用的范围不同
    wait : wait必须在同步代码块中

    sleep :可以在任何地方

  4. 是否需要捕获异常
    wait不需要捕获异常
    sleep必须捕获异常

3、Lock锁(重点)

传统Synchronized

  1. package com.cyx.demo01;
  2. //基本的卖票例子
  3. /**
  4. * 真正的多线程开发,公司中的开发
  5. * 线程就是一个单独的资源类,没有任何附属的操作!
  6. * 1、属性、方法
  7. */
  8. public class SaleTicketDemo01 {
  9. public static void main(String[] args) {
  10. //并发:多线程操作同一个资源类,把资源类丢入线程
  11. Ticket ticket = new Ticket();
  12. //@FunctionalInterface 函数式接口,jdk1.8 lambda表达式 (参数)->{代码}
  13. new Thread(() ->{
  14. for (int i = 0; i < 40; i++) {
  15. ticket.sale();
  16. }
  17. },"A").start();
  18. new Thread(() ->{
  19. for (int i = 0; i < 40; i++) {
  20. ticket.sale();
  21. }
  22. },"B").start();
  23. new Thread(() ->{
  24. for (int i = 0; i < 40; i++) {
  25. ticket.sale();
  26. }
  27. },"C").start();
  28. }
  29. }
  30. //资源类 OOP
  31. class Ticket{
  32. //属性、方法
  33. private int number = 50;
  34. //卖票的方式
  35. //synchronized 本质:队列,锁
  36. public synchronized void sale(){
  37. if(number>0){
  38. System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票,剩余:"+number);
  39. }
  40. }
  41. }

Lock 接口

image-20210524142938810.png
image-20210524143203337.png

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

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

  1. package com.cyx.demo01;
  2. import java.util.concurrent.locks.Lock;
  3. import java.util.concurrent.locks.ReentrantLock;
  4. public class SaleTicketDemo02 {
  5. public static void main(String[] args) {
  6. //并发:多线程操作同一个资源类,把资源类丢入线程
  7. Ticket2 ticket2 = new Ticket2();
  8. //@FunctionalInterface 函数式接口,jdk1.8 lambda表达式 (参数)->{代码}
  9. new Thread(() ->{ for (int i = 0; i < 40; i++) ticket2.sale(); },"A").start();
  10. new Thread(() ->{ for (int i = 0; i < 40; i++) ticket2.sale(); },"B").start();
  11. new Thread(() ->{ for (int i = 0; i < 40; i++) ticket2.sale(); },"C").start();
  12. }
  13. }
  14. // Lock三部曲
  15. // 1、new ReentrantLock();
  16. // 2、lock.lock();//加锁
  17. class Ticket2{
  18. //属性、方法
  19. private int number = 30;
  20. Lock lock = new ReentrantLock();
  21. public synchronized void sale(){
  22. lock.lock();//加锁
  23. try {
  24. if(number>0){
  25. System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票,剩余:"+number);
  26. }
  27. }catch (Exception e){
  28. e.printStackTrace();
  29. }finally {
  30. lock.unlock();//解锁
  31. }
  32. }
  33. }

Synchronized 和 Lock区别

1、Synchronized 内置的java关键字,Lock是一个java类

2、Synchronized 无法判断获取锁的状态,Lock可以判断是否获取到了锁

3、Synchronized 会自动释放锁,lock必须要手动释放锁!如果不释放锁,死锁

4、Synchronized 线程1(获得锁,阻塞)、线程2(等待,傻傻的等);Lock锁就不一定会等待下去

5、Synchronized 可重入锁,不可以中断的,非公平;Lock,可重入锁,可以判断锁,非公平(可以自己设置)

6、Synchronized 适合锁少量的代码同步问题,Lock适合锁大量的同步代码!

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

4、生产者和消费者问题

Synchronized 版

  1. package com.cyx.pc;
  2. /**
  3. * 线程之间的通信问题:生产者和消费者问题! 等待唤醒,通知唤醒
  4. * 线程交替执行 A B操作同一个变量 num=0
  5. * A num+1
  6. * B num-1
  7. */
  8. public class A {
  9. public static void main(String[] args) {
  10. Data data = new Data();
  11. new Thread(()->{
  12. for (int i = 0; i < 10; i++) {
  13. try {
  14. data.increment();
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. },"A").start();
  20. new Thread(()->{
  21. for (int i = 0; i < 10; i++) {
  22. try {
  23. data.decrement();
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. },"B").start();
  29. }
  30. }
  31. //判断等待,业务,通知
  32. class Data{//数字,资源类
  33. private int number = 0;
  34. //+1
  35. public synchronized void increment() throws InterruptedException {
  36. if(number!=0){ //0
  37. //等待
  38. this.wait();
  39. }
  40. number++;
  41. System.out.println(Thread.currentThread().getName()+"=>"+number);
  42. //通知其他线程,我+1完毕了
  43. this.notifyAll();
  44. }
  45. //-1
  46. public synchronized void decrement() throws InterruptedException {
  47. if(number==0){ //1
  48. //等待
  49. this.wait();
  50. }
  51. number--;
  52. System.out.println(Thread.currentThread().getName()+"=>"+number);
  53. //通知其他线程,我-1完毕了
  54. this.notifyAll();
  55. }
  56. }

问题存在,ABCD四个线程,虚假唤醒
image-20210524152038637.png
if 改为 while 判断

  1. package com.cyx.pc;
  2. /**
  3. * 线程之间的通信问题:生产者和消费者问题! 等待唤醒,通知唤醒
  4. * 线程交替执行 A B操作同一个变量 num=0
  5. * A num+1
  6. * B num-1
  7. */
  8. public class A {
  9. public static void main(String[] args) {
  10. Data data = new Data();
  11. new Thread(()->{
  12. for (int i = 0; i < 10; i++) {
  13. try {
  14. data.increment();
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. },"A").start();
  20. new Thread(()->{
  21. for (int i = 0; i < 10; i++) {
  22. try {
  23. data.decrement();
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. },"B").start();
  29. new Thread(()->{
  30. for (int i = 0; i < 10; i++) {
  31. try {
  32. data.increment();
  33. } catch (InterruptedException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. },"C").start();
  38. new Thread(()->{
  39. for (int i = 0; i < 10; i++) {
  40. try {
  41. data.decrement();
  42. } catch (InterruptedException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. },"D").start();
  47. }
  48. }
  49. //判断等待,业务,通知
  50. class Data{//数字,资源类
  51. private int number = 0;
  52. //+1
  53. public synchronized void increment() throws InterruptedException {
  54. while (number!=0){ //0
  55. //等待
  56. this.wait();
  57. }
  58. number++;
  59. System.out.println(Thread.currentThread().getName()+"=>"+number);
  60. //通知其他线程,我+1完毕了
  61. this.notifyAll();
  62. }
  63. //-1
  64. public synchronized void decrement() throws InterruptedException {
  65. while(number==0){ //1
  66. //等待
  67. this.wait();
  68. }
  69. number--;
  70. System.out.println(Thread.currentThread().getName()+"=>"+number);
  71. //通知其他线程,我-1完毕了
  72. this.notifyAll();
  73. }
  74. }

JUC版

image-20210524153008350.png
通过Lock找到Condition
image-20210524153042395.png

  1. package com.cyx.pc;
  2. import java.util.concurrent.locks.Condition;
  3. import java.util.concurrent.locks.Lock;
  4. import java.util.concurrent.locks.ReentrantLock;
  5. public class B {
  6. public static void main(String[] args) {
  7. Data2 data2 = new Data2();
  8. new Thread(()->{
  9. for (int i = 0; i < 10; i++) {
  10. try {
  11. data2.increment();
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. },"A").start();
  17. new Thread(()->{
  18. for (int i = 0; i < 10; i++) {
  19. try {
  20. data2.decrement();
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. },"B").start();
  26. new Thread(()->{
  27. for (int i = 0; i < 10; i++) {
  28. try {
  29. data2.increment();
  30. } catch (InterruptedException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. },"C").start();
  35. new Thread(()->{
  36. for (int i = 0; i < 10; i++) {
  37. try {
  38. data2.decrement();
  39. } catch (InterruptedException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. },"D").start();
  44. }
  45. }
  46. //判断等待,业务,通知
  47. class Data2{//数字,资源类
  48. private int number = 0;
  49. Lock lock = new ReentrantLock();
  50. Condition condition = lock.newCondition();
  51. // condition.await();//等待
  52. // condition.signalAll();//唤醒全部
  53. //+1
  54. public void increment() throws InterruptedException {
  55. lock.lock();
  56. try {
  57. //业务代码
  58. while (number!=0){ //0
  59. //等待
  60. condition.await();
  61. }
  62. number++;
  63. System.out.println(Thread.currentThread().getName()+"=>"+number);
  64. //通知其他线程,我+1完毕了
  65. condition.signalAll();
  66. } catch (Exception e) {
  67. e.printStackTrace();
  68. } finally {
  69. lock.unlock();
  70. }
  71. }
  72. //-1
  73. public void decrement() throws InterruptedException {
  74. lock.lock();
  75. try {
  76. while(number==0){ //1
  77. //等待
  78. condition.await();
  79. }
  80. number--;
  81. System.out.println(Thread.currentThread().getName()+"=>"+number);
  82. //通知其他线程,我-1完毕了
  83. condition.signalAll();
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. } finally {
  87. lock.unlock();
  88. }
  89. }
  90. }

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

Condition精准的通知和唤醒线程

image-20210524155757147.png
代码测试:

  1. package com.cyx.pc;
  2. import java.util.concurrent.locks.Condition;
  3. import java.util.concurrent.locks.Lock;
  4. import java.util.concurrent.locks.ReentrantLock;
  5. /**
  6. * @author cyx
  7. * @create 2021-05-24 15:58
  8. * A执行完调用B,B执行完调用C,C执行完调用A
  9. */
  10. public class C {
  11. public static void main(String[] args) {
  12. Data3 data3 = new Data3();
  13. new Thread(()->{
  14. for (int i = 0; i < 10; i++) {
  15. data3.printA();
  16. }
  17. },"A").start();
  18. new Thread(()->{
  19. for (int i = 0; i < 10; i++) {
  20. data3.printB();
  21. }
  22. },"B").start();
  23. new Thread(()->{
  24. for (int i = 0; i < 10; i++) {
  25. data3.printC();
  26. }
  27. },"C").start();
  28. }
  29. }
  30. class Data3{//资源类 Lock
  31. private Lock lock = new ReentrantLock();
  32. private Condition condition1 = lock.newCondition();
  33. private Condition condition2 = lock.newCondition();
  34. private Condition condition3 = lock.newCondition();
  35. private int number = 1;//1A 2B 3C
  36. public void printA(){
  37. lock.lock();
  38. try {
  39. //业务,判断->执行->通知
  40. while (number!=1){
  41. //等待
  42. condition1.await();
  43. }
  44. System.out.println(Thread.currentThread().getName()+"=>AAAAA");
  45. //唤醒,唤醒指定的人,B
  46. number = 2;
  47. condition2.signal();
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. } finally {
  51. lock.unlock();
  52. }
  53. }
  54. public void printB(){
  55. lock.lock();
  56. try {
  57. //业务,判断->执行->通知
  58. while (number != 2){
  59. condition2.await();
  60. }
  61. System.out.println(Thread.currentThread().getName()+"=>BBBBBBB");
  62. //唤醒,唤醒指定的人,c
  63. number = 3;
  64. condition3.signal();
  65. } catch (Exception e) {
  66. e.printStackTrace();
  67. } finally {
  68. lock.unlock();
  69. }
  70. }
  71. public void printC(){
  72. lock.lock();
  73. try {
  74. //业务,判断->执行->通知
  75. while (number != 3){
  76. condition3.await();
  77. }
  78. System.out.println(Thread.currentThread().getName()+"=>CCCCCCC");
  79. //唤醒,唤醒指定的人,A
  80. number = 1;
  81. condition1.signal();
  82. } catch (Exception e) {
  83. e.printStackTrace();
  84. } finally {
  85. lock.unlock();
  86. }
  87. }
  88. //生产线:下单->支付->交易->物流
  89. }

5、8锁问题

如何判断锁的是谁!永远的知道什么锁,锁到底锁的是谁!

深刻理解我们的锁

  1. package com.cyx.lock8;
  2. import java.util.concurrent.TimeUnit;
  3. /**
  4. * 8锁,就是关于锁的8个问题
  5. * 1、标准情况下,两个线程先打印 发短信还是 打电话?1、发短信 2、打电话
  6. * 2、sendSms延迟4秒,两个线程先打印 发短信还是 打电话?1、发短信 2、打电话
  7. */
  8. public class Test1 {
  9. public static void main(String[] args) {
  10. Phone phone = new Phone();
  11. //锁的存在
  12. new Thread(()->{
  13. phone.sendSms();
  14. },"A").start();
  15. //捕获
  16. try {
  17. TimeUnit.SECONDS.sleep(1);
  18. } catch (InterruptedException e) {
  19. e.printStackTrace();
  20. }
  21. new Thread(()->{
  22. phone.call();
  23. },"B").start();
  24. }
  25. }
  26. class Phone{
  27. //synchronized锁的对象是方法的调用者
  28. //两个方法用的同一个锁,谁先拿到谁执行
  29. public synchronized void sendSms(){
  30. try {
  31. TimeUnit.SECONDS.sleep(4);
  32. } catch (InterruptedException e) {
  33. e.printStackTrace();
  34. }
  35. System.out.println("发短信");
  36. }
  37. public synchronized void call(){
  38. System.out.println("打电话");
  39. }
  40. }
  1. package com.cyx.lock8;
  2. import java.util.concurrent.TimeUnit;
  3. /**
  4. * 3、增加了一个普通方法!先执行发短信还是hello?普通方法
  5. * 4、两个对象,两个同步方法,发短信还是打电话? 1、打电话 2、发短信
  6. */
  7. public class Test2 {
  8. public static void main(String[] args) {
  9. //两个对象,两个调用者,两把锁
  10. Phone2 phone1 = new Phone2();
  11. Phone2 phone2 = new Phone2();
  12. //锁的存在
  13. new Thread(()->{
  14. phone1.sendSms();
  15. },"A").start();
  16. //捕获
  17. try {
  18. TimeUnit.SECONDS.sleep(1);
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. new Thread(()->{
  23. phone2.call();
  24. },"B").start();
  25. }
  26. }
  27. class Phone2{
  28. //synchronized锁的对象是方法的调用者
  29. public synchronized void sendSms(){
  30. try {
  31. TimeUnit.SECONDS.sleep(4);
  32. } catch (InterruptedException e) {
  33. e.printStackTrace();
  34. }
  35. System.out.println("发短信");
  36. }
  37. public synchronized void call(){
  38. System.out.println("打电话");
  39. }
  40. //这里没有锁!不是同步方法,不受锁的影响
  41. public void hello(){
  42. System.out.println("hello");
  43. }
  44. }
  1. package com.cyx.lock8;
  2. import java.util.concurrent.TimeUnit;
  3. /**
  4. * 5、增加两个静态的同步方法,只有一个对象,先打印 发短信还是 打电话?1、发短信 2、打电话
  5. * 6、两个对象,增加两个静态的同步方法,只有一个对象,先打印 发短信还是 打电话?1、发短信 2、打电话
  6. */
  7. public class Test3 {
  8. public static void main(String[] args) {
  9. //两个对象的Class了模板只有一个,static,锁的是Class
  10. Phone3 phone1 = new Phone3();
  11. Phone3 phone2 = new Phone3();
  12. //锁的存在
  13. new Thread(()->{
  14. phone1.sendSms();
  15. },"A").start();
  16. //捕获
  17. try {
  18. TimeUnit.SECONDS.sleep(1);
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. new Thread(()->{
  23. phone2.call();
  24. },"B").start();
  25. }
  26. }
  27. //phone3唯一的一个Class对象
  28. class Phone3{
  29. //synchronized锁的对象是方法的调用者
  30. //static 静态方法
  31. //类一加载就有了!锁的是Class
  32. public static synchronized void sendSms(){
  33. try {
  34. TimeUnit.SECONDS.sleep(4);
  35. } catch (InterruptedException e) {
  36. e.printStackTrace();
  37. }
  38. System.out.println("发短信");
  39. }
  40. public static synchronized void call(){
  41. System.out.println("打电话");
  42. }
  43. }
  1. package com.cyx.lock8;
  2. import java.util.concurrent.TimeUnit;
  3. /**
  4. * 7、1个静态的同步方法,1个普通的同步方法,1个对象,先打印 发短信还是 打电话?1、打电话 2、发短信
  5. * 8、1个静态的同步方法,1个普通的同步方法,2个对象,先打印 发短信还是 打电话?1、打电话 2、发短信
  6. */
  7. public class Test4 {
  8. public static void main(String[] args) {
  9. //两个对象的Class了模板只有一个,static,锁的是Class
  10. Phone4 phone1 = new Phone4();
  11. Phone4 phone2 = new Phone4();
  12. //锁的存在
  13. new Thread(()->{
  14. phone1.sendSms();
  15. },"A").start();
  16. //捕获
  17. try {
  18. TimeUnit.SECONDS.sleep(1);
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. new Thread(()->{
  23. phone2.call();
  24. },"B").start();
  25. }
  26. }
  27. //phone3唯一的一个Class对象
  28. class Phone4{
  29. //静态的同步方法 锁的是Class类模板
  30. public static synchronized void sendSms(){
  31. try {
  32. TimeUnit.SECONDS.sleep(4);
  33. } catch (InterruptedException e) {
  34. e.printStackTrace();
  35. }
  36. System.out.println("发短信");
  37. }
  38. //普通的同步方法 锁的调用者
  39. public static void call(){
  40. System.out.println("打电话");
  41. }
  42. }

小结

new this 具有的一个手机

static Class 唯一的一个模板

6、集合类不安全

List不安全

  1. package com.cyx.unsafe;
  2. import java.util.*;
  3. import java.util.concurrent.CopyOnWriteArrayList;
  4. //ConcurrentModificationException 并发修改异常
  5. public class ListTest {
  6. public static void main(String[] args) {
  7. //并发下 ArrayList不安全的
  8. /**
  9. * 解决方案
  10. * 1、List<String> list = new Vector<>();
  11. * 2、List<String> list = Collections.synchronizedList(new ArrayList<>());
  12. * 3、List<String> list = new CopyOnWriteArrayList<>();
  13. */
  14. //CopyOnWrite写入时复制 COW 计算机程序设计领域的一种优化策略
  15. //多个线程调用的时候,list,读取的时候,固定的,写入(覆盖)
  16. //在写入的时候避免覆盖,造成数据问题
  17. //读写分离
  18. //CopyOnWriteArrayList 比 Vector 的优势
  19. List<String> list = new CopyOnWriteArrayList<>();
  20. for (int i = 0; i < 10; i++) {
  21. new Thread(()->{
  22. list.add(UUID.randomUUID().toString().substring(0,5));
  23. System.out.println(list);
  24. },String.valueOf(i)).start();
  25. }
  26. }
  27. }

Set不安全

  1. package com.cyx.unsafe;
  2. import java.util.Collections;
  3. import java.util.HashSet;
  4. import java.util.Set;
  5. import java.util.UUID;
  6. import java.util.concurrent.CopyOnWriteArraySet;
  7. /**
  8. * 同理可证:ConcurrentModificationException
  9. * 1、Set<String> set = Collections.synchronizedSet(new HashSet<>());
  10. * 2、Set<String> set = new CopyOnWriteArraySet<>();
  11. */
  12. public class SetList {
  13. public static void main(String[] args) {
  14. // Set<String> set = new HashSet<>();
  15. // Set<String> set = Collections.synchronizedSet(new HashSet<>());
  16. Set<String> set = new CopyOnWriteArraySet<>();
  17. for (int i = 0; i < 10; i++) {
  18. new Thread(()->{
  19. set.add(UUID.randomUUID().toString().substring(0,5));
  20. System.out.println(set);
  21. },String.valueOf(i)).start();
  22. }
  23. }
  24. }

hashSet底层是什么?

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

Map不安全

回顾map基本操作
image-20210525104922781.png

  1. package com.cyx.unsafe;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.UUID;
  5. import java.util.concurrent.ConcurrentHashMap;
  6. // ConcurrentModificationException
  7. public class MapTest {
  8. public static void main(String[] args) {
  9. //map是这样用的吗?不是,工作中不用HashMap
  10. // 默认等价于什么?new HashMap<>(16,0.75);
  11. Map<String, String> map = new ConcurrentHashMap<>();
  12. for (int i = 0; i < 30; i++) {
  13. new Thread(()->{
  14. map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
  15. System.out.println(map);
  16. },String.valueOf(i)).start();
  17. }
  18. }
  19. }

7、Callable(简单)

image-20210525105949491.png
1、可以有返回值

2、可以抛出异常

3、方法不同 ,run()/call()

代码测试

image-20210525111140172.png
image-20210525111152995.png
image-20210525112626616.png

  1. package com.cyx.Callable;
  2. import java.util.concurrent.Callable;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.FutureTask;
  5. public class CallableTest {
  6. public static void main(String[] args) throws ExecutionException, InterruptedException {
  7. //new Thread(new Runnable()).start();
  8. //new Thread(new FutureTask<V>()).start();
  9. //new Thread(new FutureTask<V>(Callable)).start();
  10. new Thread().start();//怎么启动Callable
  11. MyThread thread = new MyThread();
  12. FutureTask futureTask = new FutureTask<>(thread);
  13. new Thread(futureTask,"A").start();
  14. new Thread(futureTask,"B").start();//结果会被缓存,效率高
  15. Integer o = (Integer) futureTask.get();//这个get方法可能会产生阻塞!把他放到最后
  16. //或者使用异步通信来处理
  17. System.out.println(o);
  18. }
  19. }
  20. class MyThread implements Callable<Integer> {
  21. @Override
  22. public Integer call() throws Exception {
  23. System.out.println("call");
  24. return 1;
  25. }
  26. }

细节:

1、有缓存

2、结果可能需要等待,会阻塞。

8、常用的辅助类(必会)

8.1、CountDownLatch

image-20210526143853786.png

  1. package com.cyx.add;
  2. import java.util.concurrent.CountDownLatch;
  3. //计数器
  4. public class CountDownLatchDemo {
  5. public static void main(String[] args) throws InterruptedException {
  6. //总数是6,必须要执行任务的时候,再使用!
  7. CountDownLatch countDownLatch = new CountDownLatch(6);
  8. for (int i = 0; i < 6; i++) {
  9. new Thread(()->{
  10. System.out.println(Thread.currentThread().getName()+"go out");
  11. countDownLatch.countDown();//数量-1
  12. },String.valueOf(i)).start();
  13. }
  14. countDownLatch.await();//等待计数器归零,然后再向下走
  15. System.out.println("关门了");
  16. }
  17. }

原理:

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

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

每次有线程调用countDown()数量-1,假设计数器变为0,countDownLatch.await()就会被唤醒,继续执行!

8.2、CyclicBarrier

image-20210526144949758.png
加法计数器

  1. package com.cyx.add;
  2. import java.util.concurrent.BrokenBarrierException;
  3. import java.util.concurrent.CyclicBarrier;
  4. public class CyclicBarrierDemo {
  5. public static void main(String[] args) {
  6. /**
  7. * 集齐七颗龙珠召唤神龙
  8. */
  9. //召唤龙珠的线程
  10. CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
  11. System.out.println("召唤神龙成功");
  12. });
  13. for (int i = 0; i < 7; i++) {
  14. final int temp = i;
  15. //lambda能操作到i吗
  16. new Thread(()->{
  17. System.out.println(Thread.currentThread().getName()+"收集了"+temp+"个龙珠");
  18. try {
  19. cyclicBarrier.await();
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. } catch (BrokenBarrierException e) {
  23. e.printStackTrace();
  24. }
  25. }).start();
  26. }
  27. }
  28. }

8.3、Semaphore

Semaphore:信号量
image-20210526150435006.png
抢车位!

6车……3个停车位置

  1. package com.cyx.add;
  2. import java.util.concurrent.Semaphore;
  3. import java.util.concurrent.TimeUnit;
  4. /**
  5. * @author cyx
  6. * @create 2021-05-26 15:06
  7. */
  8. public class SemaphoreTest {
  9. public static void main(String[] args) {
  10. //线程数量:停车位! 限流!
  11. Semaphore semaphore = new Semaphore(3);
  12. for (int i = 0; i < 6; i++) {
  13. new Thread(()->{
  14. //acquire() 得到
  15. try {
  16. semaphore.acquire();
  17. System.out.println(Thread.currentThread().getName()+"抢到车位");
  18. TimeUnit.SECONDS.sleep(2);
  19. System.out.println(Thread.currentThread().getName()+"离开车位");
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. } finally {
  23. semaphore.release();
  24. }
  25. //release() 释放
  26. },String.valueOf(i)).start();
  27. }
  28. }
  29. }

原理

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

semaphore.acquire() 释放,会将当前的信号量释放+1,然后唤醒等待的线程!

9、读写锁

image-20210526153423901.png

  1. package com.cyx.rw;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.concurrent.locks.ReadWriteLock;
  5. import java.util.concurrent.locks.ReentrantReadWriteLock;
  6. /**
  7. * 独占锁(写锁) 一次只能被一个线程占有
  8. * 共享锁(读锁) 多个线程可以同时占有
  9. * ReadWriteLock
  10. * 读-读 可以共存
  11. * 读-写 不能共存
  12. * 写-写 不能共存
  13. */
  14. public class ReadWriteLockDemo {
  15. public static void main(String[] args) {
  16. MyCacheLock mycache = new MyCacheLock();
  17. //写入
  18. for (int i = 0; i < 5; i++) {
  19. final int temp = i;
  20. new Thread(() -> {
  21. mycache.put(temp + "", temp + "");
  22. }, String.valueOf(i)).start();
  23. }
  24. //读取
  25. for (int i = 0; i < 5; i++) {
  26. final int temp = i;
  27. new Thread(() -> {
  28. mycache.get(temp + "");
  29. }, String.valueOf(i)).start();
  30. }
  31. }
  32. }
  33. /**
  34. * 自定义缓存
  35. */
  36. class Mycache {
  37. private volatile Map<String, Object> map = new HashMap<>();
  38. //存,写
  39. public void put(String key, Object value) {
  40. System.out.println(Thread.currentThread().getName() + "写入" + key);
  41. map.put(key, value);
  42. System.out.println(Thread.currentThread().getName() + "写入OK");
  43. }
  44. //取,读
  45. public void get(String key) {
  46. System.out.println(Thread.currentThread().getName() + "读取" + key);
  47. Object o = map.get(key);
  48. System.out.println(Thread.currentThread().getName() + "读取OK");
  49. }
  50. }
  51. /**
  52. * 加锁的
  53. */
  54. class MyCacheLock {
  55. private volatile Map<String, Object> map = new HashMap<>();
  56. //读写锁:更加细粒度的控制
  57. private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
  58. //存,写入的时候,只希望同时只有一个线程写
  59. public void put(String key, Object value) {
  60. readWriteLock.writeLock().lock();
  61. try {
  62. System.out.println(Thread.currentThread().getName() + "写入" + key);
  63. map.put(key, value);
  64. System.out.println(Thread.currentThread().getName() + "写入OK");
  65. } catch (Exception e) {
  66. e.printStackTrace();
  67. } finally {
  68. readWriteLock.writeLock().unlock();
  69. }
  70. }
  71. //取,读,所有人都可以读!
  72. public void get(String key) {
  73. readWriteLock.readLock().lock();
  74. try {
  75. System.out.println(Thread.currentThread().getName() + "读取" + key);
  76. Object o = map.get(key);
  77. System.out.println(Thread.currentThread().getName() + "读取OK");
  78. } catch (Exception e) {
  79. e.printStackTrace();
  80. } finally {
  81. readWriteLock.readLock().unlock();
  82. }
  83. }
  84. }

10、阻塞队列

image-20210526160316420.png
阻塞队列:image-20210526160437445.png
image-20210526161619083.png
BlockQueue 不是新的东西
image-20210526161814863.png
什么情况下我们会使用阻塞队列:多线程并发处理,线程池!

学会使用队列

添加、移除

四组API

方式 抛出异常 有返回值,不抛出异常 阻塞等待 超时等待
添加 add offer() put offer(,,)
移除 remove poll() take poll(,)
检测队首元素 element peek - -
  1. package com.cyx;
  2. import java.util.concurrent.ArrayBlockingQueue;
  3. public class bq {
  4. public static void main(String[] args) {
  5. test1();
  6. }
  7. /**
  8. * 抛出异常
  9. */
  10. public static void test1(){
  11. //队列的大小
  12. ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);
  13. System.out.println(blockingQueue.add("a"));
  14. System.out.println(blockingQueue.add("b"));
  15. System.out.println(blockingQueue.add("c"));
  16. // IllegalStateException: Queue full 抛出异常
  17. //System.out.println(blockingQueue.add("d"));
  18. System.out.println("========================");
  19. System.out.println(blockingQueue.remove());
  20. System.out.println(blockingQueue.remove());
  21. System.out.println(blockingQueue.remove());
  22. // java.util.NoSuchElementException 抛出异常
  23. System.out.println(blockingQueue.remove());
  24. }
  25. }
  1. /**
  2. * 有返回值,没有异常
  3. */
  4. public static void test2(){
  5. //队列的大小
  6. ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);
  7. System.out.println(blockingQueue.offer("a"));
  8. System.out.println(blockingQueue.offer("b"));
  9. System.out.println(blockingQueue.offer("c"));
  10. //System.out.println(blockingQueue.offer("d")); //false 不抛出异常
  11. System.out.println("========================");
  12. System.out.println(blockingQueue.poll());
  13. System.out.println(blockingQueue.poll());
  14. System.out.println(blockingQueue.poll());
  15. System.out.println(blockingQueue.poll()); //null 不抛出异常
  16. }
  1. /**
  2. * 等待,阻塞(一直阻塞)
  3. */
  4. public static void test3() throws InterruptedException {
  5. //队列的大小
  6. ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);
  7. //一直阻塞
  8. blockingQueue.put("a");
  9. blockingQueue.put("b");
  10. blockingQueue.put("c");
  11. //blockingQueue.put("d");//队列没有位置了,一直阻塞
  12. System.out.println(blockingQueue.take());
  13. System.out.println(blockingQueue.take());
  14. System.out.println(blockingQueue.take());
  15. System.out.println(blockingQueue.take()); //没有这个元素,一直阻塞
  16. }
  1. /**
  2. * 等待,阻塞(一等待超时)
  3. */
  4. public static void test4() throws InterruptedException {
  5. //队列的大小
  6. ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);
  7. //一直阻塞
  8. blockingQueue.offer("a");
  9. blockingQueue.offer("b");
  10. blockingQueue.offer("c");
  11. //blockingQueue.offer("d",2, TimeUnit.SECONDS);//等待超过两秒就退出
  12. System.out.println("==================");
  13. System.out.println(blockingQueue.poll());
  14. System.out.println(blockingQueue.poll());
  15. System.out.println(blockingQueue.poll());
  16. System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
  17. }

SynchronousQueue 同步队列

没有容量,

进去一个元素,必须等待取出来之后,才能再往里再放一个元素!

put、take

  1. package com.cyx.bq;
  2. import java.util.concurrent.SynchronousQueue;
  3. import java.util.concurrent.TimeUnit;
  4. /**
  5. * 同步队列
  6. * 和其他的BlockingQueue 不一样,SynchronousQueue不存储元素
  7. * put了一个元素,必须从里面先take取出来,否则不能再put进去值
  8. */
  9. public class SynchronousQueueDemo {
  10. public static void main(String[] args) {
  11. SynchronousQueue<String> synchronousQueue = new SynchronousQueue(); //同步队列
  12. new Thread(()->{
  13. try {
  14. System.out.println(Thread.currentThread().getName()+"put 1");
  15. synchronousQueue.put("1");
  16. System.out.println(Thread.currentThread().getName()+"put 2");
  17. synchronousQueue.put("2");
  18. System.out.println(Thread.currentThread().getName()+"put 3");
  19. synchronousQueue.put("3");
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. }
  23. },"T1").start();
  24. new Thread(()->{
  25. try {
  26. TimeUnit.SECONDS.sleep(3);
  27. System.out.println(Thread.currentThread().getName()+"=>"+synchronousQueue.take());
  28. TimeUnit.SECONDS.sleep(3);
  29. System.out.println(Thread.currentThread().getName()+"=>"+synchronousQueue.take());
  30. TimeUnit.SECONDS.sleep(3);
  31. System.out.println(Thread.currentThread().getName()+"=>"+synchronousQueue.take());
  32. } catch (InterruptedException e) {
  33. e.printStackTrace();
  34. }
  35. },"T2").start();
  36. }
  37. }

11、线程池(重点)

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

池化技术

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

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

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

线程池的好处:

1、降低资源的消耗

2、提高响应的速度

3、方便管理。

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

三大方法

image-20210527103649862.png

  1. package com.cyx.pool;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. //Executors 工具类、3大方法
  5. public class Demo01 {
  6. public static void main(String[] args) {
  7. // ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程
  8. // ExecutorService threadPool = Executors.newFixedThreadPool(5);//创建一个固定的线程池的大小
  9. ExecutorService threadPool = Executors.newCachedThreadPool();//可伸缩的,遇强则强,遇弱则弱
  10. try {
  11. for (int i = 0; i < 10; i++) {
  12. //使用了线程池之后,使用线程池来创建线程
  13. threadPool.execute(()->{
  14. System.out.println(Thread.currentThread().getName()+"ok");
  15. });
  16. }
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. } finally {
  20. //线程池用完,程序结束,关闭线程池
  21. threadPool.shutdown();
  22. }
  23. }
  24. }

7大参数

  1. public static ExecutorService newSingleThreadExecutor() {
  2. return new FinalizableDelegatedExecutorService
  3. (new ThreadPoolExecutor(1, 1,
  4. 0L, TimeUnit.MILLISECONDS,
  5. new LinkedBlockingQueue<Runnable>()));
  6. }
  7. public static ExecutorService newFixedThreadPool(int nThreads) {
  8. return new ThreadPoolExecutor(nThreads, nThreads,
  9. 0L, TimeUnit.MILLISECONDS,
  10. new LinkedBlockingQueue<Runnable>());
  11. }
  12. public static ExecutorService newCachedThreadPool() {
  13. return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
  14. 60L, TimeUnit.SECONDS,
  15. new SynchronousQueue<Runnable>());
  16. }
  17. //本质:ThreadPoolExecutor()
  18. public ThreadPoolExecutor(int corePoolSize, //核心线程池大小
  19. int maximumPoolSize, //最大线程池大小
  20. long keepAliveTime, //超时了没有人调用就会释放
  21. TimeUnit unit, //超时单位
  22. BlockingQueue<Runnable> workQueue, //阻塞队列
  23. ThreadFactory threadFactory, //线程工厂,创建线程的,一般不用动
  24. RejectedExecutionHandler handler //拒绝策略) {
  25. if (corePoolSize < 0 ||
  26. maximumPoolSize <= 0 ||
  27. maximumPoolSize < corePoolSize ||
  28. keepAliveTime < 0)
  29. throw new IllegalArgumentException();
  30. if (workQueue == null || threadFactory == null || handler == null)
  31. throw new NullPointerException();
  32. this.acc = System.getSecurityManager() == null ?
  33. null :
  34. AccessController.getContext();
  35. this.corePoolSize = corePoolSize;
  36. this.maximumPoolSize = maximumPoolSize;
  37. this.workQueue = workQueue;
  38. this.keepAliveTime = unit.toNanos(keepAliveTime);
  39. this.threadFactory = threadFactory;
  40. this.handler = handler;
  41. }

image-20210527114124371.png
image-20210527114547617.png

手动创建一个线程池

  1. package com.cyx.pool;
  2. import java.util.concurrent.*;
  3. //Executors 工具类、3大方法
  4. /**
  5. * new ThreadPoolExecutor.AbortPolicy()//银行满了,还有人进来,不处理这个人的,抛出异常
  6. * new ThreadPoolExecutor.CallerRunsPolicy()//哪来的去哪里!
  7. * new ThreadPoolExecutor.DiscardPolicy()//队列满了,丢掉任务,不会抛出异常!
  8. * new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试去和最早的竞争,也不会抛出异常!
  9. */
  10. public class Demo01 {
  11. //自定义线程池!工作 ThreadPoolExecutor
  12. public static void main(String[] args) {
  13. ExecutorService threadPool = new ThreadPoolExecutor(
  14. 2,
  15. 5,
  16. 3,
  17. TimeUnit.SECONDS,
  18. new LinkedBlockingDeque<>(3),
  19. Executors.defaultThreadFactory(),
  20. new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试去和最早的竞争,也不会抛出异常!
  21. );
  22. try {
  23. //最大承载:Deuqe + max
  24. //超过 RejectedExecutionException
  25. for (int i = 0; i < 10; i++) {
  26. //使用了线程池之后,使用线程池来创建线程
  27. threadPool.execute(()->{
  28. System.out.println(Thread.currentThread().getName()+"ok");
  29. });
  30. }
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. } finally {
  34. //线程池用完,程序结束,关闭线程池
  35. threadPool.shutdown();
  36. }
  37. }
  38. }

4种拒绝策略

image-20210527133448278.png

  1. /**
  2. * new ThreadPoolExecutor.AbortPolicy()//银行满了,还有人进来,不处理这个人的,抛出异常
  3. * new ThreadPoolExecutor.CallerRunsPolicy()//哪来的去哪里!
  4. * new ThreadPoolExecutor.DiscardPolicy()//队列满了,丢掉任务,不会抛出异常!
  5. * new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试去和最早的竞争,也不会抛出异常!
  6. */

小结和拓展

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

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

  1. package com.cyx.pool;
  2. import java.util.concurrent.*;
  3. public class Demo01 {
  4. //自定义线程池!工作 ThreadPoolExecutor
  5. public static void main(String[] args) {
  6. // 最大线程到底该如何定义
  7. // 1、CPU密集型,几核,就是几,可以保持CPU的效率最高!
  8. // 2、IO 密集型 >判断你程序中十分耗IO的线程,
  9. // 程序 15个大型任务 io十分占用资源!
  10. // 获取CPU的核数
  11. System.out.println(Runtime.getRuntime().availableProcessors());
  12. ExecutorService threadPool = new ThreadPoolExecutor(
  13. 2,
  14. 5,
  15. 3,
  16. TimeUnit.SECONDS,
  17. new LinkedBlockingDeque<>(3),
  18. Executors.defaultThreadFactory(),
  19. new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试去和最早的竞争,也不会抛出异常!
  20. );
  21. try {
  22. //最大承载:Deuqe + max
  23. //超过 RejectedExecutionException
  24. for (int i = 0; i < 10; i++) {
  25. //使用了线程池之后,使用线程池来创建线程
  26. threadPool.execute(()->{
  27. System.out.println(Thread.currentThread().getName()+"ok");
  28. });
  29. }
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. } finally {
  33. //线程池用完,程序结束,关闭线程池
  34. threadPool.shutdown();
  35. }
  36. }
  37. }

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

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

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

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

.image-20210527135332226.png

代码测试

Function函数式接口

image-20210527141824389.png

  1. package com.cyx.function;
  2. import java.util.function.Function;
  3. /**
  4. * Function 函数型接口,有一个输入参数,有一个输出
  5. * 只要是 函数型接口 可以用lambda表达式简化
  6. */
  7. public class Demo01 {
  8. public static void main(String[] args) {
  9. //工具类:输出 输入的值
  10. // Function function = new Function<String,String>() {
  11. // @Override
  12. // public String apply(String str) {
  13. // return str;
  14. // }
  15. // };
  16. Function<String,String> function = (str)->{
  17. return str;
  18. };
  19. System.out.println(function.apply("asd"));
  20. }
  21. }

断定型接口

image-20210527142326559.png

  1. package com.cyx.function;
  2. import java.util.function.Predicate;
  3. /**
  4. * 断定型接口:有一个输入参数,返回值只能是布尔值
  5. */
  6. public class Demo02 {
  7. public static void main(String[] args) {
  8. //判断字符串是否为空
  9. // Predicate<String> predicate = new Predicate<String>() {
  10. // @Override
  11. // public boolean test(String str) {
  12. // return str.isEmpty();
  13. // }
  14. // };
  15. Predicate<String> predicate = (str)->{
  16. return str.isEmpty();
  17. };
  18. System.out.println(predicate.test(""));
  19. }
  20. }

Consumer消费型接口

image-20210527143941987.png

  1. package com.cyx.function;
  2. import java.util.function.Consumer;
  3. /**
  4. * Consumer 消费型接口:只有输入,没有返回值
  5. */
  6. public class Demo03 {
  7. public static void main(String[] args) {
  8. // Consumer<String> consumer = new Consumer<String>() {
  9. // @Override
  10. // public void accept(String s) {
  11. // System.out.println(s);
  12. // }
  13. // };
  14. Consumer<String> consumer = (s)->{
  15. System.out.println(s);
  16. };
  17. consumer.accept("asd");
  18. }
  19. }

Supplier供给型接口

image-20210527144319551.png

  1. package com.cyx.function;
  2. import java.util.function.Supplier;
  3. /**
  4. * Supplier 供给型接口 没有参数 只有返回值
  5. */
  6. public class Demo04 {
  7. public static void main(String[] args) {
  8. // Supplier<Integer> supplier = new Supplier<Integer>() {
  9. // @Override
  10. // public Integer get() {
  11. // return 1024;
  12. // }
  13. // };
  14. Supplier<Integer> supplier = ()->{return 1024;};
  15. System.out.println(supplier.get());
  16. }
  17. }

13、Stream流式计算

什么是Stream流式计算

大数据:存储 + 计算

集合、MySQL本质就是存储东西的;

计算都应该交给流来操作!

  1. package com.cyx.Stream;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. /**
  5. * 题目要求:一分钟内完成此题,只能用一行代码实现!
  6. * 现在有五个用户!筛选:
  7. * 1、ID必须是偶数
  8. * 2、年龄必须大于23岁
  9. * 3、用户名转为大写字母
  10. * 4、用户名字母倒着排序
  11. * 5、只输出一个用户!
  12. */
  13. public class Test {
  14. public static void main(String[] args) {
  15. User u1 = new User(1, "a", 21);
  16. User u2 = new User(2, "b", 22);
  17. User u3 = new User(3, "c", 23);
  18. User u4 = new User(4, "d", 24);
  19. User u6 = new User(6, "e", 25);
  20. //集合就是存储
  21. List<User> list = Arrays.asList(u1, u2, u3, u4, u6);
  22. //计算交给Stream流
  23. //lambda表达式、链式编程、函数式接口、Stream流式计算
  24. list.stream()
  25. .filter(u->{return u.getId()%2==0;})
  26. .filter(u->{return u.getAge()>23;})
  27. .map(u->{return u.getName().toUpperCase();})
  28. .sorted((uu1,uu2)->{return uu2.compareTo(uu1);})
  29. .limit(1)
  30. .forEach(System.out::println);
  31. }
  32. }

14、ForkJoin

什么是ForkJoin

ForkJoin在jdk1.7,并行执行任务!提高效率,大数据量!

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

image-20210527151853081.png

ForkJoin特点:工作窃取

这个里面维护的都是双端队列
image-20210527152154614.png

ForkJoin操作

image-20210527153036020.png
image-20210527153044418.png

  1. package com.cyx.FrokJoin;
  2. import java.util.concurrent.RecursiveTask;
  3. /**
  4. * 求和计算的任务!
  5. * 3000 6000(ForkJoin) 9000(Stream并行流)
  6. * 如何使用ForkJoin
  7. * 1、ForkJoinPool 通过它来执行
  8. * 2、计算任务forkJoinPool.execute(ForkJoinTask task)
  9. * 3、计算类要继承ForkJoinTask
  10. */
  11. public class ForkJoinDemo extends RecursiveTask<Long> {
  12. private Long start; //1
  13. private Long end; //1990900000
  14. //临界值
  15. private Long temp = 10000L;
  16. public ForkJoinDemo(Long start, Long end) {
  17. this.start = start;
  18. this.end = end;
  19. }
  20. //计算方法
  21. @Override
  22. protected Long compute() {
  23. if((end-start)<temp){
  24. Long sum = 0L;
  25. for (Long i = start; i <= end; i++) {
  26. sum += i;
  27. }
  28. return sum;
  29. }else {//ForkJoin
  30. long middle = (start+end)/2;//中间值
  31. ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
  32. ForkJoinDemo task2 = new ForkJoinDemo(middle+1, end);
  33. task1.fork();//拆分任务,把任务压入线程队列
  34. task2.fork();
  35. return task1.join() + task2.join();
  36. }
  37. }
  38. }
  1. package com.cyx.FrokJoin;
  2. import java.util.concurrent.ExecutionException;
  3. import java.util.concurrent.ForkJoinPool;
  4. import java.util.concurrent.ForkJoinTask;
  5. import java.util.stream.LongStream;
  6. public class Test {
  7. public static void main(String[] args) throws ExecutionException, InterruptedException {
  8. test1();//5428
  9. test2();//4812
  10. test3();//146
  11. }
  12. public static void test1(){
  13. Long sum = 0L;
  14. long start = System.currentTimeMillis();
  15. for (Long i = 1L; i <= 10_0000_0000; i++) {
  16. sum += i;
  17. }
  18. long end = System.currentTimeMillis();
  19. System.out.println("sum="+sum+"时间"+(end-start));
  20. }
  21. public static void test2() throws ExecutionException, InterruptedException {
  22. long start = System.currentTimeMillis();
  23. ForkJoinPool forkJoinPool = new ForkJoinPool();
  24. ForkJoinTask<Long> task = new ForkJoinDemo(0L, 10_0000_0000L);
  25. ForkJoinTask<Long> submit = forkJoinPool.submit(task);//提交任务
  26. long sum = submit.get();
  27. long end = System.currentTimeMillis();
  28. System.out.println("sum="+sum+"时间"+(end-start));
  29. }
  30. public static void test3(){
  31. long start = System.currentTimeMillis();
  32. //Stream并行流 range() rangeClosed(]
  33. long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
  34. long end = System.currentTimeMillis();
  35. System.out.println("sum="+sum+"时间"+(end-start));
  36. }
  37. }

15、异步回调

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

  1. package com.cyx.Future;
  2. import java.util.concurrent.CompletableFuture;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.Future;
  5. import java.util.concurrent.TimeUnit;
  6. /**
  7. * 异步调用:CompletableFuture
  8. * //异步执行
  9. * //成功回调
  10. * //失败回调
  11. */
  12. public class Demo01 {
  13. public static void main(String[] args) throws ExecutionException, InterruptedException {
  14. //没有返回值的runAsync异步回调
  15. // CompletableFuture<Void> completableFuture =CompletableFuture.runAsync(()->{
  16. // try {
  17. // TimeUnit.SECONDS.sleep(2);
  18. // } catch (InterruptedException e) {
  19. // e.printStackTrace();
  20. // }
  21. // System.out.println(Thread.currentThread().getName()+"runAsync->Void");
  22. // });
  23. //
  24. // System.out.println("1111");
  25. // completableFuture.get();//阻塞获取执行结果
  26. //有返回值的supplyAsync异步回调
  27. //ajax,成功和失败的回调
  28. //返回的是错误信息;
  29. CompletableFuture<Integer> completableFuture =CompletableFuture.supplyAsync(()->{
  30. System.out.println(Thread.currentThread().getName()+"supplyAsync->Integer");
  31. int i = 10/0;
  32. return 1024;
  33. });
  34. System.out.println(completableFuture.whenComplete((t, u) -> {
  35. System.out.println("t=>" + t); //正确的返回结果
  36. System.out.println("u=>" + u); //错误信息:java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
  37. }).exceptionally((e) -> {
  38. System.out.println(e.getMessage());
  39. return 233;
  40. }).get());
  41. }
  42. }

16、JMM

请你谈谈对Volatile的理解

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

1、保证可见性

2、不保证原子性

3、禁止指令重排

什么是JMM

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

关于JMM的一些同步的约定

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

2、线程加锁前,必须读取主存中的最新值到工作内存中!

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

线程 工作内存 主内存

8种操作:
image-20210527172224445.png
image-20210527172439089.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操作之前,必须把此变量同步回主内存

问题:程序不知道主内存的值已经被修改过了
image-20210527173022883.png

17、Volatile

保证可见性

  1. package com.cyx.tvolatile;
  2. import java.util.concurrent.TimeUnit;
  3. public class JMMDemo {
  4. //不加 volatile 程序就会死循环!
  5. //加 volatile 可以保证可见性
  6. private volatile static int num = 0;
  7. public static void main(String[] args) { //main
  8. new Thread(()->{ //线程1对主内存的变化不知道的
  9. while (num==0){
  10. }
  11. }).start();
  12. try {
  13. TimeUnit.SECONDS.sleep(1);
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. num = 1;
  18. System.out.println(num);
  19. }
  20. }

不保证原子性

原子性:不可分割

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

  1. package com.cyx.tvolatile;
  2. //不保证原子性
  3. public class VDemo02 {
  4. //volatile不保证原子性
  5. private volatile static int num = 0;
  6. public static void add(){
  7. num++;
  8. }
  9. public static void main(String[] args) {
  10. //理论上num结果应该为2万
  11. for (int i = 0; i < 20; i++) {
  12. new Thread(()->{
  13. for (int j = 0; j < 1000; j++) {
  14. add();
  15. }
  16. }).start();
  17. }
  18. while (Thread.activeCount()>2){ //main gc
  19. Thread.yield();
  20. }
  21. System.out.println(Thread.currentThread().getName()+" "+num);
  22. }
  23. }

如果不加lock和synchronized,怎么保证原子性
image-20210528111010646.png
使用原子类,解决原子性问题
image-20210528111234619.png

  1. package com.cyx.tvolatile;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. //不保证原子性
  4. public class VDemo02 {
  5. //volatile不保证原子性
  6. private volatile static AtomicInteger num = new AtomicInteger();
  7. public static void add(){
  8. // num++;//不是一个原子性操作
  9. num.getAndIncrement();// AtomicInteger + 1方法,CAS
  10. }
  11. public static void main(String[] args) {
  12. //理论上num结果应该为2万
  13. for (int i = 0; i < 20; i++) {
  14. new Thread(()->{
  15. for (int j = 0; j < 1000; j++) {
  16. add();
  17. }
  18. }).start();
  19. }
  20. while (Thread.activeCount()>2){ //main gc
  21. Thread.yield();
  22. }
  23. System.out.println(Thread.currentThread().getName()+" "+num);
  24. }
  25. }

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

指令重排

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

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

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

  1. int x = 1; //1
  2. int y = 2; //2
  3. x = x + 5; //3
  4. y = x * x; //4
  5. 我们所期望的:1234 但是可能执行的时候会变成 2134 1324
  6. 不可能是 4123!

可能造成影响的结果:abxy这四个值默认都是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-20210528113619593.png
Volatile是可以保证 可见性 。不能保证原子性,由于内存屏障,可以保证避免指令重排的现象产生!

18、彻底玩转单例模式

饿汉式、DCL懒汉式 ,深究!

饿汉式

  1. package com.cyx.single;
  2. //饿汉式单例
  3. public class Hungry {
  4. //可能会浪费空间
  5. private byte[] data1 = new byte[1024*1024];
  6. private byte[] data2 = new byte[1024*1024];
  7. private byte[] data3 = new byte[1024*1024];
  8. private byte[] data4 = new byte[1024*1024];
  9. private Hungry(){
  10. }
  11. private final static Hungry HUNGRY = new Hungry();
  12. public static Hungry getInstance(){
  13. return HUNGRY;
  14. }
  15. }

DCL懒汉式

  1. package com.cyx.single;
  2. import java.lang.reflect.Constructor;
  3. import java.lang.reflect.Field;
  4. //懒汉式单例
  5. //道高一尺魔高一丈
  6. public class LazyMan {
  7. private static boolean cyx = false;
  8. private LazyMan(){
  9. synchronized (LazyMan.class){
  10. if(cyx == false){
  11. cyx = true;
  12. }else {
  13. throw new RuntimeException("不要试图使用反射破坏单例");
  14. }
  15. }
  16. System.out.println(Thread.currentThread().getName()+"ok");
  17. };
  18. private volatile static LazyMan lazyMan;
  19. //双重检测锁模式的 懒汉式单例 DCL懒汉式
  20. public static LazyMan getInstance(){
  21. if(lazyMan == null){
  22. synchronized (LazyMan.class){
  23. if(lazyMan == null){
  24. lazyMan = new LazyMan(); //不是一个原子性操作
  25. }
  26. }
  27. }
  28. return lazyMan;
  29. }
  30. //反射!
  31. public static void main(String[] args) throws Exception {
  32. Field cyx = LazyMan.class.getDeclaredField("cyx");
  33. cyx.setAccessible(true);
  34. // LazyMan instance = LazyMan.getInstance();
  35. Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
  36. declaredConstructor.setAccessible(true);
  37. LazyMan instance = declaredConstructor.newInstance();
  38. cyx.set(instance,false);
  39. LazyMan instance2 = declaredConstructor.newInstance();
  40. System.out.println(instance);
  41. System.out.println(instance2);
  42. }
  43. }
  44. /**
  45. * 1、分配内存空间
  46. * 2、执行构造方法,初始化对象
  47. * 3、把这个对象指向这个空间
  48. *
  49. * 123
  50. * 132 A
  51. * B //此时lazyMan还没有完成构造
  52. */

静态内部类

  1. package com.cyx.single;
  2. //静态内部类
  3. public class Holder {
  4. private Holder(){
  5. };
  6. public static Holder getInstance(){
  7. return InnerClass.HOLDER;
  8. }
  9. public static class InnerClass{
  10. private static final Holder HOLDER = new Holder();
  11. }
  12. }

单例不安全,因为有反射

枚举

  1. package com.cyx.single;
  2. import java.lang.reflect.Constructor;
  3. import java.lang.reflect.InvocationTargetException;
  4. // enum 是一个什么? 本身也是一个Class类
  5. public enum EnumSingle {
  6. INSTANCE;
  7. public EnumSingle getInstance(){
  8. return INSTANCE;
  9. }
  10. }
  11. class Test{
  12. public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
  13. EnumSingle instance1 = EnumSingle.INSTANCE;
  14. Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class,int.class);
  15. declaredConstructor.setAccessible(true);
  16. EnumSingle instance2 = declaredConstructor.newInstance();
  17. //NoSuchMethodException: com.cyx.single.EnumSingle.<init>()
  18. System.out.println(instance1);
  19. System.out.println(instance2);
  20. }
  21. }

image-20210528153614955.png
枚举类型的最终反编译源码

  1. public abstract class Enum<E extends Enum<E>>
  2. implements Comparable<E>, Serializable {
  3. private final String name;
  4. public final String name() {
  5. return name;
  6. }
  7. private final int ordinal;
  8. public final int ordinal() {
  9. return ordinal;
  10. }
  11. protected Enum(String name, int ordinal) {
  12. this.name = name;
  13. this.ordinal = ordinal;
  14. }
  15. public String toString() {
  16. return name;
  17. }
  18. public final boolean equals(Object other) {
  19. return this==other;
  20. }
  21. public final int hashCode() {
  22. return super.hashCode();
  23. }
  24. protected final Object clone() throws CloneNotSupportedException {
  25. throw new CloneNotSupportedException();
  26. }
  27. public final int compareTo(E o) {
  28. Enum<?> other = (Enum<?>)o;
  29. Enum<E> self = this;
  30. if (self.getClass() != other.getClass() && // optimization
  31. self.getDeclaringClass() != other.getDeclaringClass())
  32. throw new ClassCastException();
  33. return self.ordinal - other.ordinal;
  34. }
  35. @SuppressWarnings("unchecked")
  36. public final Class<E> getDeclaringClass() {
  37. Class<?> clazz = getClass();
  38. Class<?> zuper = clazz.getSuperclass();
  39. return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;
  40. }
  41. public static <T extends Enum<T>> T valueOf(Class<T> enumType,
  42. String name) {
  43. T result = enumType.enumConstantDirectory().get(name);
  44. if (result != null)
  45. return result;
  46. if (name == null)
  47. throw new NullPointerException("Name is null");
  48. throw new IllegalArgumentException(
  49. "No enum constant " + enumType.getCanonicalName() + "." + name);
  50. }
  51. protected final void finalize() { }
  52. private void readObject(ObjectInputStream in) throws IOException,
  53. ClassNotFoundException {
  54. throw new InvalidObjectException("can't deserialize enum");
  55. }
  56. private void readObjectNoData() throws ObjectStreamException {
  57. throw new InvalidObjectException("can't deserialize enum");
  58. }
  59. }

19、深入理解CAS

什么是CAS

  1. package com.cyx.cas;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. public class CASDemo {
  4. //CAS compareAndSet:比较并交换
  5. public static void main(String[] args) {
  6. AtomicInteger atomicInteger = new AtomicInteger(2020);
  7. //期望、更新
  8. //public final boolean compareAndSet(int expect, int update)
  9. //如果我期望的值达到了,那么就更新,否则,就不更新 ,CAS是CPU的并发原语!
  10. System.out.println(atomicInteger.compareAndSet(2020, 2021));
  11. System.out.println(atomicInteger.get());
  12. atomicInteger.getAndIncrement();//++
  13. System.out.println(atomicInteger.compareAndSet(2020, 2021));
  14. System.out.println(atomicInteger.get());
  15. }
  16. }

unsafe类

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

缺点:
1、循环会耗时

2、一次性只能保证一个共享变量的原子性

3、ABA问题

CAS:ABA问题(狸猫换太子)

image-20210528161528822.png

  1. package com.cyx.cas;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. public class CASDemo {
  4. //CAS compareAndSet:比较并交换
  5. public static void main(String[] args) {
  6. AtomicInteger atomicInteger = new AtomicInteger(2020);
  7. //期望、更新
  8. //public final boolean compareAndSet(int expect, int update)
  9. //如果我期望的值达到了,那么就更新,否则,就不更新 ,CAS是CPU的并发原语!
  10. // --------------捣乱的线程----------------
  11. System.out.println(atomicInteger.compareAndSet(2020, 2021));
  12. System.out.println(atomicInteger.get());
  13. System.out.println(atomicInteger.compareAndSet(2021, 2020));
  14. System.out.println(atomicInteger.get());
  15. // --------------期望的线程----------------
  16. System.out.println(atomicInteger.compareAndSet(2020, 6666));
  17. System.out.println(atomicInteger.get());
  18. }
  19. }

20、原子引用

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

带版本号的原子操作!

  1. package com.cyx.cas;
  2. import java.util.concurrent.TimeUnit;
  3. import java.util.concurrent.atomic.AtomicStampedReference;
  4. public class CASDemo {
  5. public static void main(String[] args) {
  6. //注意,如果泛型是一个包装类,注意对象的引用问题
  7. //正常在业务操作里,这里面比较的都是一个个对象
  8. AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(1, 1);
  9. new Thread(()->{
  10. int stamp = atomicStampedReference.getStamp(); //获得版本号
  11. System.out.println("a1=>"+stamp);
  12. try {
  13. TimeUnit.SECONDS.sleep(1);
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. System.out.println(atomicStampedReference.compareAndSet(1, 2,
  18. atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
  19. System.out.println("a2=>"+atomicStampedReference.getStamp());
  20. System.out.println(atomicStampedReference.compareAndSet(2, 1,
  21. atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
  22. System.out.println("a3=>"+atomicStampedReference.getStamp());
  23. },"a").start();
  24. new Thread(()->{
  25. int stamp = atomicStampedReference.getStamp(); //获得版本号
  26. System.out.println("b1=>"+stamp);
  27. try {
  28. TimeUnit.SECONDS.sleep(2);
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. }
  32. System.out.println(atomicStampedReference.compareAndSet(1, 6,
  33. stamp, stamp + 1));
  34. System.out.println("b2=>"+atomicStampedReference.getStamp());
  35. },"b").start();
  36. }
  37. }

注意:

Integer使用了对象缓存机制,默认范围是-128~127,推荐使用静态工厂方法valueOf获取对象实例,而不是new,

因为valueOf使用缓存,而new一定会创建新的对象分配新的内存空间。
image-20210528165623961.png

21、各种锁的理解

1、公平锁、非公平锁

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

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

  1. public ReentrantLock(){
  2. sync = new NonfairSync();
  3. }
  4. public ReentrantLock(boolean fair){
  5. sync = fair ? new FairSync() : new NonfairSync();
  6. }

2、可重入锁

可重入锁(递归锁)
image-20210528170304600.png

Synchronized

  1. package com.cyx.lock;
  2. // Synchronized
  3. public class Demo01 {
  4. public static void main(String[] args) {
  5. Phone phone = new Phone();
  6. new Thread(()->{
  7. phone.sms();
  8. },"a").start();
  9. new Thread(()->{
  10. phone.sms();
  11. },"b").start();
  12. }
  13. }
  14. class Phone{
  15. public synchronized void sms(){
  16. System.out.println(Thread.currentThread().getName()+"sms");
  17. call();//这里也有锁
  18. }
  19. public synchronized void call(){
  20. System.out.println(Thread.currentThread().getName()+"call");
  21. }
  22. }

Lock

  1. package com.cyx.lock;
  2. import java.util.concurrent.locks.Lock;
  3. import java.util.concurrent.locks.ReentrantLock;
  4. public class Demo02 {
  5. public static void main(String[] args) {
  6. Phone2 phone = new Phone2();
  7. new Thread(()->{
  8. phone.sms();
  9. },"a").start();
  10. new Thread(()->{
  11. phone.sms();
  12. },"b").start();
  13. }
  14. }
  15. class Phone2{
  16. Lock lock = new ReentrantLock();
  17. public synchronized void sms(){
  18. lock.lock();// 细节问题:lock.lock();lock.unlock();
  19. lock.lock();
  20. try {
  21. System.out.println(Thread.currentThread().getName()+"sms");
  22. call();//这里也有锁
  23. }catch (Exception e){
  24. e.printStackTrace();
  25. }
  26. finally {
  27. lock.unlock();
  28. lock.unlock();
  29. }
  30. }
  31. public synchronized void call(){
  32. lock.lock();
  33. try {
  34. System.out.println(Thread.currentThread().getName()+"sms");
  35. }catch (Exception e){
  36. e.printStackTrace();
  37. }
  38. finally {
  39. lock.unlock();
  40. }
  41. }
  42. }

3、自旋锁

spinlock
image-20210528171352068.png
自定义一个锁

  1. package com.cyx.lock;
  2. import java.util.concurrent.atomic.AtomicReference;
  3. //自旋锁
  4. public class SpinlockDemo {
  5. //int 0
  6. //Thread null
  7. AtomicReference<Thread> atomicReference = new AtomicReference<>();
  8. //加锁
  9. public void myLock(){
  10. Thread thread = Thread.currentThread();
  11. System.out.println(Thread.currentThread().getName()+ "===>mylock");
  12. //自旋锁
  13. while (!atomicReference.compareAndSet(null,thread)){
  14. }
  15. }
  16. //解锁
  17. public void myUnLock(){
  18. Thread thread = Thread.currentThread();
  19. System.out.println(Thread.currentThread().getName()+ "===>myUnLock");
  20. atomicReference.compareAndSet(thread,null);
  21. }
  22. }

测试:

  1. package com.cyx.lock;
  2. import java.util.concurrent.TimeUnit;
  3. /**
  4. * @author cyx
  5. * @create 2021-05-28 17:21
  6. */
  7. public class TestSpinLock {
  8. public static void main(String[] args) throws InterruptedException {
  9. //底层使用的自旋锁
  10. SpinlockDemo lock = new SpinlockDemo();
  11. new Thread(()->{
  12. lock.myLock();
  13. try {
  14. TimeUnit.SECONDS.sleep(5);
  15. } catch (Exception e) {
  16. e.printStackTrace();
  17. } finally {
  18. lock.myUnLock();
  19. }
  20. },"t1").start();
  21. TimeUnit.SECONDS.sleep(3);
  22. new Thread(()->{
  23. lock.myLock();
  24. try {
  25. TimeUnit.SECONDS.sleep(1);
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. } finally {
  29. lock.myUnLock();
  30. }
  31. },"t2").start();
  32. }
  33. }

4、死锁

  1. package com.cyx.lock;
  2. import java.util.concurrent.TimeUnit;
  3. public class DeadLockDemo {
  4. public static void main(String[] args) {
  5. String lockA = "lockA";
  6. String lockB = "lockB";
  7. new Thread(new MyThread(lockA,lockB),"T1").start();
  8. new Thread(new MyThread(lockB,lockA),"T2").start();
  9. }
  10. }
  11. class MyThread implements Runnable{
  12. private String lockA;
  13. private String lockB;
  14. public MyThread(String lockA, String lockB) {
  15. this.lockA = lockA;
  16. this.lockB = lockB;
  17. }
  18. @Override
  19. public void run() {
  20. synchronized (lockA){
  21. System.out.println(Thread.currentThread().getName()+"lock"+lockA+"=>"+lockB);
  22. try {
  23. TimeUnit.SECONDS.sleep(2);
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. synchronized ((lockB)){
  28. System.out.println(Thread.currentThread().getName()+"lock"+lockB+"=>"+lockA);
  29. }
  30. }
  31. }
  32. }

解决问题

1、使用jps -l定位进程号
image-20210531101212111.png

2、使用jstack 进程号找到死锁问题
image-20210531101345960.png