JUC(并发编程)

article/2025/10/12 6:10:57

该笔记大部分搬运B站遇见狂神说的javaJUC,顺便把图文合并记录,便于回顾
视频地址:【狂神说Java】JUC并发编程最新版通俗易懂_哔哩哔哩_bilibili记得三连


        目录

                1.什么是JUC?

                2.线程进程和程序

                3.Lock锁(重点) 

                4.生产者和消费者问题!

                5.八锁现象

                6.集合安全问题 

                7.Callable (简单)

                8.常用辅助类(必会)

                9.读写锁

                10.阻塞队列

                11.线程池(重点)

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

                13.Stream流式计算

                14.ForkJoin

                 15.异步回调

                16.JMM 


1.什么是JUC?

JUC是指javaUtil包中的三个操作线程的包!

2.线程进程和程序

程序(Program):是一个静态的概念,一般对应于操作系统中的一个可执行的文件
,比如:我们要启动酷狗听音乐,则对应酷狗可执行程序。当我们双击酷狗,则加载
程序到内存中,开始执行该程序,于是产生了"进程".

进程:执行中的程序叫做进程(Process),是一个动态的概念。现代的操作系统都可以同时启动多个进程。比如:我们在用酷狗听音乐,也可以使用wps写文档,也可以同时用浏览器查看网页。可以通过任务管理器查看当前的进程.

线程:是进程的一个执行路径,一个进程中至少有一个线程,进程中的多个线程共享进程的资源。

java默认有两个线程:main(主)现场和GC(垃圾回收)线程

提问:java真的可以开启线程吗?开启不了! 

    public synchronized void start() {/*** This method is not invoked for the main method thread or "system"* group threads created/set up by the VM. Any new functionality added* to this method in the future may have to also be added to the VM.** A zero status value corresponds to state "NEW".*/if (threadStatus != 0)throw new IllegalThreadStateException();/* Notify the group that this thread is about to be started* so that it can be added to the group's list of threads* and the group's unstarted count can be decremented. */group.add(this);boolean started = false;try {start0();started = true;} finally {try {if (!started) {group.threadStartFailed(this);}} catch (Throwable ignore) {/* do nothing. If start0 threw a Throwable thenit will be passed up the call stack */}}}//这是一个C++底层,Java是没有权限操作底层硬件的private native void start0();

Java是没有权限去开启线程、操作硬件的,这是一个native的一个本地方法,它调用的底层的C++代码。

并发、并行

并发: 多线程操作同一个资源。

  • CPU 只有一核,模拟出来多条线程,天下武功,唯快不破。那么我们就可以使用CPU快速交替,来模拟多线程。

并行: 多个人(CPU内核)一起行走(运行)

  • CPU多核,多个线程可以同时执行。 我们可以使用线程池!
public class Test1 {public static void main(String[] args) {//获取cpu的核数System.out.println(Runtime.getRuntime().availableProcessors());}
}

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

线程有几个状态?

线程的状态:6个状态

public enum State {/*** Thread state for a thread which has not yet started.*///运行(新生,就绪)NEW,/*** Thread state for a runnable thread.  A thread in the runnable* state is executing in the Java virtual machine but it may* be waiting for other resources from the operating system* such as processor.*///运行RUNNABLE,/*** Thread state for a thread blocked waiting for a monitor lock.* A thread in the blocked state is waiting for a monitor lock* to enter a synchronized block/method or* reenter a synchronized block/method after calling* {@link Object#wait() Object.wait}.*///阻塞BLOCKED,/*** Thread state for a waiting thread.* A thread is in the waiting state due to calling one of the* following methods:* <ul>*   <li>{@link Object#wait() Object.wait} with no timeout</li>*   <li>{@link #join() Thread.join} with no timeout</li>*   <li>{@link LockSupport#park() LockSupport.park}</li>* </ul>** <p>A thread in the waiting state is waiting for another thread to* perform a particular action.** For example, a thread that has called <tt>Object.wait()</tt>* on an object is waiting for another thread to call* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on* that object. A thread that has called <tt>Thread.join()</tt>* is waiting for a specified thread to terminate.*///等待WAITING,/*** Thread state for a waiting thread with a specified waiting time.* A thread is in the timed waiting state due to calling one of* the following methods with a specified positive waiting time:* <ul>*   <li>{@link #sleep Thread.sleep}</li>*   <li>{@link Object#wait(long) Object.wait} with timeout</li>*   <li>{@link #join(long) Thread.join} with timeout</li>*   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>*   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>* </ul>*///超时等待TIMED_WAITING,/*** Thread state for a terminated thread.* The thread has completed execution.*///终止TERMINATED;}

wait/sleep的区别?

1、来自不同的类

wait => Object        

sleep => Thread      

一般情况企业中使用休眠是:

TimeUnit.DAYS.sleep(1); //休眠1天
TimeUnit.SECONDS.sleep(1); //休眠1s

2、关于锁的释放

wait 释放锁睡;

sleep 抱着锁睡;

3、使用的范围是不同的

wait 必须在同步代码块中;

sleep 可以在任何地方睡;

4、是否需要捕获异常

wait是不需要捕获异常(中断异常除外,所有线程都有中断异常);

sleep必须要捕获异常;

3.Lock锁(重点) 

 传统:synchronized

package com.test.demo;/*** 基本的卖票例子* 记住:线程就是一个单独的资源类,没用任何的附属操作!*/
public class Demo01{public static void main(String[] args) {//多线程操作Ticket ticket = new Ticket();new Thread(()-> { for (int i = 0; i < 60; i++) ticket.sale(); },"A").start();new Thread(()-> { for (int i = 0; i < 60; i++) ticket.sale(); },"B").start();new Thread(()-> { for (int i = 0; i < 60; i++) ticket.sale(); },"C").start();new Thread(()-> { for (int i = 0; i < 60; i++) ticket.sale(); },"D").start();}
}//资源类
class Ticket{private static int number=50;//卖票方式public synchronized void sale(){if (number>0){System.out.println(Thread.currentThread().getName() + "购买了第" + (number--) + "张票,剩余票数为"+number);}}
}

 Lock接口

公平锁:十分公平,必须先来后到~

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

package com.test.demo;import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;/*** 基本的卖票例子* 记住:线程就是一个单独的资源类,没用任何的附属操作!*/
public class Demo01{public static void main(String[] args) {//多线程操作Ticket ticket = new Ticket();new Thread(()-> { for (int i = 0; i < 60; i++) ticket.sale(); },"A").start();new Thread(()-> { for (int i = 0; i < 60; i++) ticket.sale(); },"B").start();new Thread(()-> { for (int i = 0; i < 60; i++) ticket.sale(); },"C").start();new Thread(()-> { for (int i = 0; i < 60; i++) ticket.sale(); },"D").start();}
}//资源类
class Ticket{private static int number=50;Lock lock= new ReentrantLock();//卖票方式public void sale(){//加锁lock.lock();try {if (number>0){System.out.println(Thread.currentThread().getName() + "购买了第" + (number--) + "张票,剩余票数为"+number);}} finally {//解锁lock.unlock();}}
}

synchronized锁与Lock锁的区别

  1. synchronized是内置的java关键字而Lock是一个接口
  2. synchronized无法判断获取锁的状态,Lock可以判断是否获取到了锁
  3. synchronized会自动释放锁,Lock必须要手动释放锁!否则会造成死锁.
  4. synchronized 线程1(获得锁,阻塞),线程2(等待,傻傻的等);Lock锁就不会一直等下去
  5. synchronized 可重入锁 不可以中断的 非公平,Lock 可重入锁 可以判断的 非公平(可以设置)
  6. synchronized 适合锁少量同步代码,Lock适合锁大量同步代码.

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

个人理解:锁是一种用于解决安全的机制,java中锁一般都是锁的对象,或者锁的是需要进行增删改的属性或发方法.

4.生产者和消费者问题!

synchronized版

package JUC.PC;public class A {public static void main(String[] args) {Data data = new Data();new Thread(()->{try {for (int i = 0; i < 20; i++) {data.Production();}} catch (InterruptedException e) {e.printStackTrace();}},"A").start();new Thread(()->{try {for (int i = 0; i < 20; i++) {data.Consumption();}} catch (InterruptedException e) {e.printStackTrace();}},"B").start();}
}//资源类
class Data {private int number = 0;//生产public synchronized void Production() throws InterruptedException {if (number != 0) {this.wait();}number++;System.out.println(Thread.currentThread().getName()+"线程生产+1,目前总数"+number);this.notifyAll();}//消费public synchronized void Consumption() throws InterruptedException {if (number==0){this.wait();}number--;System.out.println(Thread.currentThread().getName()+"线程消费-1,目前总数"+number);this.notifyAll();}
}

 如果有ABCD4个线程则会出现问题!虚假唤醒!

解决方案:将if改为while即可

package JUC.PC;public class A {public static void main(String[] args) {Data data = new Data();new Thread(() -> {try {for (int i = 0; i < 20; i++) {data.Production();}} catch (InterruptedException e) {e.printStackTrace();}}, "A").start();new Thread(() -> {try {for (int i = 0; i < 20; i++) {data.Consumption();}} catch (InterruptedException e) {e.printStackTrace();}}, "B").start();new Thread(() -> {try {for (int i = 0; i < 20; i++) {data.Production();}} catch (InterruptedException e) {e.printStackTrace();}}, "C").start();new Thread(() -> {try {for (int i = 0; i < 20; i++) {data.Consumption();}} catch (InterruptedException e) {e.printStackTrace();}}, "D").start();}
}//资源类
class Data {private int number = 0;//生产public synchronized void Production() throws InterruptedException {while (number != 0) {this.wait();}number++;System.out.println(Thread.currentThread().getName() + "线程生产+1,目前总数" + number);this.notifyAll();}//消费public synchronized void Consumption() throws InterruptedException {while (number == 0) {this.wait();}number--;System.out.println(Thread.currentThread().getName() + "线程消费-1,目前总数" + number);this.notifyAll();}
}

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

 

package JUC.PC;import java.lang.management.LockInfo;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class A {public static void main(String[] args) {Data data = new Data();new Thread(() -> {try {for (int i = 0; i < 20; i++) {data.Production();}} catch (InterruptedException e) {e.printStackTrace();}}, "A").start();new Thread(() -> {try {for (int i = 0; i < 20; i++) {data.Consumption();}} catch (InterruptedException e) {e.printStackTrace();}}, "B").start();new Thread(() -> {try {for (int i = 0; i < 20; i++) {data.Production();}} catch (InterruptedException e) {e.printStackTrace();}}, "C").start();new Thread(() -> {try {for (int i = 0; i < 20; i++) {data.Consumption();}} catch (InterruptedException e) {e.printStackTrace();}}, "D").start();}
}//资源类
class Data {private int number = 0;Lock reentrantLock = new ReentrantLock();Condition condition = reentrantLock.newCondition();//生产public void Production() throws InterruptedException {try {reentrantLock.lock();while (number != 0) {condition.await();}number++;System.out.println(Thread.currentThread().getName() + "线程生产+1,目前总数" + number);condition.signalAll();} finally {reentrantLock.unlock();}}//消费public void Consumption() throws InterruptedException {try {reentrantLock.lock();while (number == 0) {condition.await();}number--;System.out.println(Thread.currentThread().getName() + "线程消费-1,目前总数" + number);condition.signalAll();} finally {reentrantLock.unlock();}}
}

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

Condition 精准通知和唤醒线程

 

 可以定义多个监视器进行精准通知如:

package JUC.PC;import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class B {public static void main(String[] args) {Data01 data01 = new Data01();new Thread(() -> {for (int i = 0; i < 10; i++) {data01.printA();}}, "A").start();new Thread(() -> {for (int i = 0; i < 10; i++) {data01.printB();}}, "B").start();new Thread(() -> {for (int i = 0; i < 10; i++) {data01.printC();}}, "C").start();new Thread(() -> {for (int i = 0; i < 10; i++) {data01.printD();}}, "D").start();}
}class Data01 {//可重入锁private final Lock lock = new ReentrantLock();//监视器private final Condition condition1 = lock.newCondition();private final Condition condition2 = lock.newCondition();private final Condition condition3 = lock.newCondition();private final Condition condition4 = lock.newCondition();//物品数量private int count = 0;//生产public void printA() {lock.lock();try {while (count != 0) {//等待condition1.await();}count++;System.out.println(Thread.currentThread().getName() + "生产物品数量+1物品还剩" + count + "个,通知B消费");//唤醒Bcondition2.signal();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}//消费public void printB() {lock.lock();try {while (count <= 0) {condition2.await();}count--;System.out.println(Thread.currentThread().getName() + "消费物品数量-1物品还剩" + count + "个,通知C生产");//通知Ccondition3.signal();} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}}//生产public void printC() {try {lock.lock();while (count != 0) {//等待condition3.await();}count++;System.out.println(Thread.currentThread().getName() + "生产物品数量+1物品还剩" + count + "个,通知D消费");//唤醒Dcondition4.signal();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}//消费public void printD() {lock.lock();try {while (count <= 0) {condition4.await();}count--;System.out.println(Thread.currentThread().getName() + "消费物品数量-1物品还剩" + count + "个,通知A生产");//通知Acondition1.signal();} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}}
}

 5.八锁现象

如何判断锁的是什么?

 锁对象或class对象!

问题1:在标准情况下,两个线程是先发短信还是先打电话?

package JUC.Lock8;import java.util.concurrent.TimeUnit;/*** 8锁,就是关于锁的八个问题* 1.在标准情况下,两个线程是先发短信还是先打电话?    先发短信*/
public class Test1 {public static void main(String[] args) throws InterruptedException {Phone phone = new Phone();new Thread(() -> {phone.sendSms();}, "A").start();TimeUnit.SECONDS.sleep(1);new Thread(() -> {phone.call();}, "B").start();}
}class Phone {//发短信public synchronized void sendSms()  {System.out.println("发短信中...");}//打电话public synchronized void call() {System.out.println("打电话中...");}
}

问题2:在sendSms方法延迟了4秒后的情况下,两个线程是先发短信还是先打电话?

package JUC.Lock8;import java.util.concurrent.TimeUnit;/*** 8锁,就是关于锁的八个问题* 1.在标准情况下,两个线程是先发短信还是先打电话?    先发短信* 2.在sendSms方法延迟了4秒后的情况下,两个线程是先发短信还是先打电话?    先发短信,因为两个方法都是同一个对象所以代表着谁先拿到锁谁就先执行*/
public class Test1 {public static void main(String[] args) throws InterruptedException {Phone phone = new Phone();new Thread(() -> {try {phone.sendSms();} catch (InterruptedException e) {e.printStackTrace();}}, "A").start();TimeUnit.SECONDS.sleep(1);new Thread(() -> {phone.call();}, "B").start();}
}class Phone {//发短信 public synchronized void sendSms() throws InterruptedException {TimeUnit.SECONDS.sleep(4);System.out.println("发短信中...");}//打电话public synchronized void call() {System.out.println("打电话中...");}}

问题3:这里输出发短信还是hello?

package JUC.Lock8;import java.util.concurrent.TimeUnit;/*** 8锁,就是关于锁的八个问题* 1.在标准情况下,两个线程是先发短信还是先打电话?    先发短信* 2.在sendSms方法延迟了4秒后的情况下,两个线程是先发短信还是先打电话?    先发短信,因为两个方法都是同一个对象所以代表着谁先拿到锁谁就先执行* 3.这里输出发短信还是hello?    hello 因为着hello这个方法并没有上锁,且发短信的方法以及拉到了锁但是需要睡眠4秒所以是hello*/
public class Test1 {public static void main(String[] args) throws InterruptedException {Phone phone = new Phone();new Thread(() -> {try {phone.sendSms();} catch (InterruptedException e) {e.printStackTrace();}}, "A").start();TimeUnit.SECONDS.sleep(1);new Thread(() -> {phone.hello();}, "B").start();}
}class Phone {//发短信public synchronized void sendSms() throws InterruptedException {TimeUnit.SECONDS.sleep(4);System.out.println("发短信中...");}//打电话public synchronized void call() {System.out.println("打电话中...");}public void hello(){System.out.println("hello");}
}

问题四:有两个对象先执行发短信还是打电话? 

package JUC.Lock8;import java.util.concurrent.TimeUnit;/*** 8锁,就是关于锁的八个问题* 1.在标准情况下,两个线程是先发短信还是先打电话?    先发短信* 2.在sendSms方法延迟了4秒后的情况下,两个线程是先发短信还是先打电话?    先发短信,因为两个方法都是同一个对象所以代表着谁先拿到锁谁就先执行* 3.这里输出发短信还是hello?    hello 因为着hello这个方法并没有上锁,且发短信的方法以及拉到了锁但是需要睡眠4秒所以是hello* 4.有两个对象先执行发短信还是打电话? 打电话,应为这里有了两个对象将不在受锁的影响,而sendSms方法中又睡眠的4秒所以是先打电话*/
public class Test1 {public static void main(String[] args) throws InterruptedException {//两个对象Phone phone = new Phone();Phone phone01 = new Phone();new Thread(() -> {try {phone.sendSms();} catch (InterruptedException e) {e.printStackTrace();}}, "A").start();TimeUnit.SECONDS.sleep(1);new Thread(() -> {phone01.call();}, "B").start();}
}class Phone {//发短信public synchronized void sendSms() throws InterruptedException {TimeUnit.SECONDS.sleep(4);System.out.println("发短信中...");}//打电话public synchronized void call() {System.out.println("打电话中...");}
}

5.增加两个静态同步方法,只有一个对象,先发短信还是先打电话? 

package JUC.Lock8;import java.util.concurrent.TimeUnit;/*** 8锁,就是关于锁的八个问题* 5.增加两个静态同步方法,只有一个对象,先发短信还是先打电话? 发短信,因为静态的方法从属于类则锁锁的就是类了,而sendSms短信是最先拿到锁的*/
public class Test2 {public static void main(String[] args) throws InterruptedException {//两个对象Phone phone = new Phone();new Thread(() -> {try {phone.sendSms();} catch (InterruptedException e) {e.printStackTrace();}}, "A").start();TimeUnit.SECONDS.sleep(1);new Thread(() -> {phone.call();}, "B").start();}
}class Phone {//发短信public static synchronized void sendSms() throws InterruptedException {TimeUnit.SECONDS.sleep(4);System.out.println("发短信中...");}//打电话public static synchronized void call() {System.out.println("打电话中...");}
}

6.增加两个静态同步方法,两个个对象,先发短信还是先打电话? 

package JUC.Lock8;import java.util.concurrent.TimeUnit;/*** 8锁,就是关于锁的八个问题* 6.增加两个静态同步方法,两个个对象,先发短信还是先打电话? 发短信,因为静态的方法从属于类则锁锁的就是类了,而sendSms短信是最先拿到锁的*/
public class Test3 {public static void main(String[] args) throws InterruptedException {//两个对象Phone phone = new Phone();Phone phone02 = new Phone();new Thread(() -> {try {phone.sendSms();} catch (InterruptedException e) {e.printStackTrace();}}, "A").start();TimeUnit.SECONDS.sleep(1);new Thread(() -> {phone02.call();}, "B").start();}
}class Phone {//发短信public static synchronized void sendSms() throws InterruptedException {TimeUnit.SECONDS.sleep(4);System.out.println("发短信中...");}//打电话public static synchronized void call() {System.out.println("打电话中...");}
}

 7.一个静态同步方法,一个非静态同步方法,只有一个对象,先发短信还是先打电话?

package JUC.Lock8;import java.util.concurrent.TimeUnit;/*** 8锁,就是关于锁的八个问题* 7.一个静态同步方法,一个非静态同步方法,只有一个对象,先发短信还是先打电话? 打电话,因为一个锁的是class一个锁的是对象,但是发短信会延迟4秒而打电话只延迟一秒所以是打电话.*/
public class Test4 {public static void main(String[] args) throws InterruptedException {//两个对象Phone phone = new Phone();new Thread(() -> {try {phone.sendSms();} catch (InterruptedException e) {e.printStackTrace();}}, "A").start();TimeUnit.SECONDS.sleep(1);new Thread(() -> {phone.call();}, "B").start();}
}class Phone {//发短信public static synchronized void sendSms() throws InterruptedException {TimeUnit.SECONDS.sleep(4);System.out.println("发短信中...");}//打电话public synchronized void call() {System.out.println("打电话中...");}
}

8. 一个静态同步方法,一个非静态同步方法,两个对象,先发短信还是先打电话?

package JUC.Lock8;import java.util.concurrent.TimeUnit;/*** 8锁,就是关于锁的八个问题* 8.一个静态同步方法,一个非静态同步方法,两个对象,先发短信还是先打电话? 打电话,因为一个锁的是class一个锁的是对象,但是发短信会延迟4秒而打电话只延迟一秒所以是打电话.*/
public class Test4 {public static void main(String[] args) throws InterruptedException {//两个对象Phone phone = new Phone();Phone phone02 = new Phone();new Thread(() -> {try {phone.sendSms();} catch (InterruptedException e) {e.printStackTrace();}}, "A").start();TimeUnit.SECONDS.sleep(1);new Thread(() -> {phone02.call();}, "B").start();}
}class Phone {//发短信public static synchronized void sendSms() throws InterruptedException {TimeUnit.SECONDS.sleep(4);System.out.println("发短信中...");}//打电话public synchronized void call() {System.out.println("打电话中...");}
}

 小结:

  • 如果是非静态的synchronized是锁的调用它的对象!
  • 如果为静态的synchronized是锁的是Class类模板! 

6.集合安全问题 

 List

当在单线程中List是安全的,但在并发中ArrayList是不安全的如:

package JUC.List;import java.util.ArrayList;
import java.util.List;
import java.util.UUID;public class TestList {public static void main(String[] args) {List<String> list = new ArrayList<>();for (int i = 1; i <= 100; i++) {new Thread(()->{list.add(UUID.randomUUID().toString().substring(0, 10));System.out.println(list);},String.valueOf(i)).start();}}
}

 就会出现了:ConcurrentModificationException(并发修改异常),解决方案:

  • 使用synchronized给ArrayList的add方法加锁(ArrayList是1.2出来的)
  • 使用List的子类Vector集合类着里面加入了synchronized(Vector是1.0出来的)
  • 使用Collections.synchronizedList()方法将集合转换为安全的集合
  • 使用CopyOnWriteArrayList类在java并发包concurrent下!

这里推荐使用CopyOnWriteArrayList因为:

  • 不同于Vector,它并不是锁的对象,而是锁了进行修改的数组,提高了效率
  • 它的add方法对传入的数据进行了Copy然后才进行保存,提高了安全。
package JUC.List;import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;public class TestList {public static void main(String[] args) {List<String> list = new CopyOnWriteArrayList<>();for (int i = 1; i <= 100; i++) {new Thread(()->{list.add(UUID.randomUUID().toString().substring(0, 10));System.out.println(list);},String.valueOf(i)).start();}}
}

 Set

package JUC.List;import java.util.*;//同理可得:ConcurrentModificationException(并发修改异常)
public class TestList {public static void main(String[] args) {Set<String> set = new HashSet<>();for (int i = 1; i <= 100; i++) {new Thread(()->{set.add(UUID.randomUUID().toString().substring(0, 10));System.out.println(set);},String.valueOf(i)).start();}}
}

解决方案:

  • 使用Collections.synchronizedSet()方法将集合转换为安全的set集合!
  • 使用ConcurrentSkipListSet类在java并发包concurrent下!

HashSet的底层就是使用了HashMap的键去存储的!同理ConcurrentSkipListSet类的底层是使用了ConcurrentSkipListMap的键进行存储!

 Map

面试题:

Map是这样用的吗?

HashMap<Object, Object> objectObjectHashMap = new HashMap<>();

 默认等价什么?

 默认的容量为16默认的加载因子是0.75

同时HashMap也是不安全的

package JUC.List;import java.util.HashMap;
import java.util.UUID;//同理会报:ConcurrentModificationException(并发修改异常)
public class TestMap {public static void main(String[] args) {HashMap<Object, Object> hashMap = new HashMap<>();for (int i = 0; i < 100; i++) {new Thread(()->{hashMap.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 10));System.out.println(hashMap);}).start();}}
}

解决方案:

  • 使用Collections.synchronizedSortedMap()把Map转换为安全的集合
  • 使用ConcurrentHashMap类在java并发包concurrent下!

7.Callable (简单)

Callable多线程的第三种实现方式:

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

 而这样如何去调用Thread进行启动Callable线程了?

这里就有一个实现了Runnable的类叫做FutureTask类(适配器模式),它去实现了Runnable接口可以通过它去进行调用Thread.

 如:

package JUC.Callable;import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;public class TestCallable {public static void main(String[] args) throws ExecutionException, InterruptedException {//创建适配器FutureTask<Integer> futureTask = new FutureTask<>(new MyCallable());//因为FutureTask实现了RunnableFuture接口所以可以通过Thread启动线程new Thread(futureTask,"A").start();//获取线程返回值System.out.println(futureTask.get());}
}class MyCallable implements Callable<Integer> {/*** Computes a result, or throws an exception if unable to do so.** @return computed result* @throws Exception if unable to compute a result*/@Overridepublic Integer call() throws Exception {System.out.println("你好");return 1024;}
}

 细节问题:

  • 有缓存!
  • 接口可能会遭到堵塞,需要等待线程执行完毕!

 8.常用辅助类(必会)

CountDownLatch类:

 该类可以用作一个减法计数器去执行实例:

package JUC.AuxiliaryClass;import java.util.concurrent.CountDownLatch;//计数器
public class TestCountDownLatch {public static void main(String[] args) throws InterruptedException {//总数是6CountDownLatch countDownLatch = new CountDownLatch(6);for (int i = 0; i < 6; i++) {new Thread(() -> {System.out.println(Thread.currentThread().getName()+"走了");countDownLatch.countDown();//表示数量-1},String.valueOf(i)).start();}//等待计数器归零在往下执行!countDownLatch.await();System.out.println("关门!");}
}

常用方法:

  •  countDownLatch.countDown();//表示数量-1
  • countDownLatch.await();  //等待计数器归零在往下执行!

原理:当每次有线程调用 countDown()方法则数量减一,假设数量变为0,await()方法就会被唤醒继续执行!

CyclicBarrier类

加法计数器:

package JUC.AuxiliaryClass;import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;public class TestSemaphore {public static void main(String[] args) {//线程数量,停车位,限流的时候会用Semaphore semaphore = new Semaphore(3);for (int i = 0; i < 8; i++) {new Thread(()->{//acquire() 得到//release() 释放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();}}).start();}}
}

Semaphore类 

实例:

package JUC.AuxiliaryClass;import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;public class TestSemaphore {public static void main(String[] args) {//线程数量,停车位,限流的时候会用Semaphore semaphore = new Semaphore(3);for (int i = 0; i < 8; i++) {new Thread(()->{//acquire() 得到//release() 释放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();}}).start();}}
}

 常用方法:

  • semaphore.acquire(); //获得
  • semaphore.release(); //释放

原理:使用acquire()方法获取一个资源,如果没有则等待,release()释放资源则资源+1.

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

9.读写锁

ReadWriteLock

 ReadWriteLock叫做读写锁是java.util.concurrent.locks包下的,它的写锁可以进行一次只被一个线程共享的操作,读锁则可以被所有线程共享,锁已又称为,独占锁(写锁)和共享锁(读锁),如:

package JUC.Lock;import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;/*** 小结:* 独占锁(写锁):一次只能被一个线程占用* 共享锁(读锁):多线程可以同时占有* 读-读:可以共存!* 读-写:不能共存!* 写-写:不能共存!*/
public class TestReadWriteLock {public static void main(String[] args) {MyCacheLock myCache = new MyCacheLock();//存写的线程for (int i = 0; i < 5; i++) {int temp=i;new Thread(()->{myCache .put(String.valueOf(temp),temp);},String.valueOf(i)).start();}//读写的线程for (int i = 0; i < 5; i++) {int temp=i;new Thread(()->{myCache.get(String.valueOf(temp));},String.valueOf(i)).start();}}
}/*** 自定义缓存*/
class MyCache{private volatile HashMap<String,Object> map=new HashMap<>();//存写public void put(String key,Object value){System.out.println(Thread.currentThread().getName()+"正在写入"+key+":"+value);map.put(key,value);System.out.println(Thread.currentThread().getName()+"写入完毕");}//读取public void get(String key){System.out.println(Thread.currentThread().getName()+"正在读取"+key);Object o = map.get(key);System.out.println(Thread.currentThread().getName()+"读取完毕");}
}/*** 加锁的自定义缓存*/
class MyCacheLock{private volatile HashMap<String,Object> map=new HashMap<>();//读写锁,更加细腻度的控制private final ReentrantReadWriteLock lock=new ReentrantReadWriteLock();//存写 (存写的时候只希望有一个线程进行)public void put(String key,Object value){//上一把写锁lock.writeLock().lock();try {System.out.println(Thread.currentThread().getName()+"正在写入"+key+":"+value);map.put(key,value);System.out.println(Thread.currentThread().getName()+"写入完毕");} finally {lock.writeLock().unlock();}}//读取 (所有人都可以读)public void get(String key){lock.readLock().lock();try {System.out.println(Thread.currentThread().getName()+"正在读取"+key);Object o = map.get(key);System.out.println(Thread.currentThread().getName()+"读取完毕");} finally {lock.readLock().unlock();}}
}

 10.阻塞队列

 

BlockingQueue不是新的东西同它的老祖宗也继承了Collection接口(同时也继承了Queue队列接口))

 什么情况下会使用堵塞队列?

  • 多线程并发处理
  • 线程池!

 使用队列

 四组API:

方式        抛出异常有返回值,不抛出异常阻塞 等待超时等待
添加addofferput        offer(等待时间,等待单位)
移除removepolltakepoll(等待时间,等待单位)

检测队首元素

elementpeekpeekpeek
    //会抛出异常public static void test1(){ArrayBlockingQueue<Object> objects = new ArrayBlockingQueue<>(3);System.out.println(objects.add("a"));System.out.println(objects.add("b"));System.out.println(objects.add("c"));//IllegalStateException: Queue full(队列已满异常!)//System.out.println(objects.add("d"));System.out.println("===================");System.out.println(objects.remove());System.out.println(objects.remove());System.out.println(objects.remove());//NoSuchElementException(队列为空异常!)//System.out.println(objects.remove());}
    //有返回值.不抛出异常public static void test2(){ArrayBlockingQueue<Object> objects = new ArrayBlockingQueue<>(3);System.out.println(objects.offer("a"));System.out.println(objects.offer("b"));System.out.println(objects.offer("c"));System.out.println(objects.offer("d"));//falseSystem.out.println("===================");System.out.println(objects.poll());System.out.println(objects.poll());System.out.println(objects.poll());System.out.println(objects.poll());//null}
    //等待,阻塞(一直阻塞)public static void test3() throws InterruptedException {ArrayBlockingQueue<Object> arrayBlockingQueue = new ArrayBlockingQueue<>(3);arrayBlockingQueue.put("a");arrayBlockingQueue.put("b");arrayBlockingQueue.put("c");//arrayBlockingQueue.put("d");//队列没有位置了则会等待System.out.println(arrayBlockingQueue.take());System.out.println(arrayBlockingQueue.take());System.out.println(arrayBlockingQueue.take());//System.out.println(arrayBlockingQueue.take()); //队列没有元素了则会等待}
    //超时等待public static void test4() throws InterruptedException {ArrayBlockingQueue<Object> arrayBlockingQueue = new ArrayBlockingQueue<>(3);System.out.println(arrayBlockingQueue.offer("a"));System.out.println(arrayBlockingQueue.offer("b"));System.out.println(arrayBlockingQueue.offer("c"));System.out.println(arrayBlockingQueue.offer("d", 2, TimeUnit.SECONDS));//等待超过两秒就退出System.out.println("===================");System.out.println(arrayBlockingQueue.poll());System.out.println(arrayBlockingQueue.poll());System.out.println(arrayBlockingQueue.poll());System.out.println(arrayBlockingQueue.poll(2, TimeUnit.SECONDS));//等待超过两秒就退出}

SynchronousQueue(同步队列)

 没有容量,当进去一个元素必须等待取出才能再次进入元素!

package JUC.Queue;import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;public class TestSynchronousQueue {public static void main(String[] args) throws InterruptedException {SynchronousQueue<Object> objects = new SynchronousQueue<>();new Thread(()->{try {objects.put("a");System.out.println(Thread.currentThread().getName()+"put a");objects.put("b");System.out.println(Thread.currentThread().getName()+"put b");objects.put("c");System.out.println(Thread.currentThread().getName()+"put c");} catch (InterruptedException e) {e.printStackTrace();}},"T1").start();new Thread(()->{try {TimeUnit.SECONDS.sleep(3);System.out.println(Thread.currentThread().getName()+"->"+objects.take());TimeUnit.SECONDS.sleep(3);System.out.println(Thread.currentThread().getName()+"->"+objects.take());TimeUnit.SECONDS.sleep(3);System.out.println(Thread.currentThread().getName()+"->"+objects.take());} catch (InterruptedException e) {e.printStackTrace();}},"T2").start();}
}

11.线程池(重点)

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

 池化技术

当程序允许时需要的链接如:JDBC链接,IO链接等等他们开启或关闭会极大的耗费资源,这时则引入了一个池化技术的概念。

池化技术本质:事先准备好一些资源,要用的时候来这里取,用完了在放回去,这样就不用一直开启关闭浪费资源了.

线程池的好处: 

  • 降低资源消耗
  • 效率大大提升
  • 方便我们管理

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

线程池三大方法 

package JUC.Queue;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;/*** 三大方法*/
public class TestExecutors {public static void main(String[] args) {
//        ExecutorService executorService = Executors.newSingleThreadExecutor();//单个线程
//        ExecutorService executorService = Executors.newFixedThreadPool(100);//固定线程池大写ExecutorService executorService = Executors.newCachedThreadPool();//可伸缩的线程池try {for (int i = 0; i < 100; i++) {executorService.execute(()->{System.out.println(Thread.currentThread().getName());});}} finally {//线程池用完一定要关闭executorService.shutdown();}}
}

 七大参数

源码分析:

    //单个线程    public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));}//固定线程池大写public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}//可伸缩的线程池public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE, //这里最大核心线程约为21亿!60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}//本质开启线程池调用了ThreadPoolExecutor()public ThreadPoolExecutor(int corePoolSize, //核心线程池大小int maximumPoolSize,    //最大核心线程池大小long keepAliveTime,     //超时了没有人调用就会释放TimeUnit unit,          //超时单位BlockingQueue<Runnable> workQueue, //阻塞队列ThreadFactory threadFactory,       //线程工厂,创建线程的,一般不动用RejectedExecutionHandler handler) { //拒绝策略if (corePoolSize < 0 ||maximumPoolSize <= 0 ||maximumPoolSize < corePoolSize ||keepAliveTime < 0)throw new IllegalArgumentException();if (workQueue == null || threadFactory == null || handler == null)throw new NullPointerException();this.corePoolSize = corePoolSize;this.maximumPoolSize = maximumPoolSize;this.workQueue = workQueue;this.keepAliveTime = unit.toNanos(keepAliveTime);this.threadFactory = threadFactory;this.handler = handler;}

 阿里规范手册!

 手动创建一个线程池 

package JUC.Queue;import java.util.concurrent.*;public class TestThreadPoolExecutor {public static void main(String[] args) {/*** 四种拒绝策略* 1.new ThreadPoolExecutor.AbortPolicy() //线程满了还有线程要进入则,不做处理,直接抛出异常* 2.new ThreadPoolExecutor.CallerRunsPolicy() //那来的那里去* 3.new ThreadPoolExecutor.DiscardPolicy() //队列满了丢掉任务,直接开摆,不会抛出异常!* 4.new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了,尝试去和最早的竞争,也不会抛出异常!*/ThreadPoolExecutor executor = new ThreadPoolExecutor(2,5,2,TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());//队列满了,尝试去和最早的竞争,也不会抛出异常!for (int i = 0; i < 19; i++) {executor.execute(()->{System.out.println(Thread.currentThread().getName()+"线程");});}}
}

四种拒绝策略

  • new ThreadPoolExecutor.AbortPolicy() //线程满了还有线程要进入则,不做处理,直接抛出异常
  • new ThreadPoolExecutor.CallerRunsPolicy() //那来的那里去
  • new ThreadPoolExecutor.DiscardPolicy() //队列满了丢掉任务,直接开摆,不会抛出异常!
  • new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了,尝试去和最早的竞争,也不会抛出异常!

小结和拓展: 

池的最大的线程如何去设置? 

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

package JUC.Queue;import java.util.concurrent.*;public class TestThread {public static void main(String[] args) {/*** 最大线程到底该如何定义?* CPU密集型:CPU几核就是几 可以使用Runtime.getRuntime().availableProcessors()方法检测出电脑是几核的* IO密集型:判断程序中十分消耗资源的IO有多少个最大线程数大于它就好了(最好是它的两倍)*/new ThreadPoolExecutor(1,Runtime.getRuntime().availableProcessors(),1,TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());}
}

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

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

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

 如: 

package java.lang;@FunctionalInterface
public interface Runnable {public abstract void run();
}
/*** FunctionalInterface超级多* 它简化了编程模板,在新版的框架底层大量运用* forEach(消费者类的函数式接口)*/

Function函数式接口

package JUC.FunctionInterface;import java.util.function.Function;//Function测试
public class TestFunction {public static void main(String[] args) {//使用匿名内部类表示Function<Integer, String> function = new Function<>() {@Overridepublic String apply(Integer o) {if (o!=null){return String.valueOf(o);}else {return null;}}};//使用lambda表达式优化Function<Integer,String> lambda=o->String.valueOf(o);System.out.println(lambda.apply(16));}
}

断定型接口:Predicate

package JUC.FunctionInterface;import java.util.Objects;
import java.util.function.Predicate;/*** 断定型接口:有一个输入参数返回值只能是Boolean值*/
public class TestPredicate {public static void main(String[] args) {Predicate<String> predicate = new Predicate<>() {@Overridepublic boolean test(String o) {return o.isEmpty();}};//简化Predicate<String> predicate1=(o)->{return o.isEmpty()};}
}

供给型接口:

package JUC.FunctionInterface;import java.util.function.Supplier;//供给型接口:只有返回值没有参数列表
public class TestSupplier {public static void main(String[] args) {Supplier<String> supplier = new Supplier<>() {@Overridepublic String get() {return "你好";}};//简化Supplier<String> s=()-> "你好";}
}

 13.Stream流式计算

什么是Stream计算 

 我们一些的集合与Mysql数据库本质是用来存储数据的,计算都应该交给流来操作!

package JUC.Stream;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;/*** 题目:一分钟内完成此题,并且只能用一行代码来实现* 1.ID为偶数* 2.年龄必须大于23* 3.用户名转换为大写字母,并返回* 4.用户名字母倒着排序* 5.只输出一个用户*/
public class practice<T> {public static void main(String[] args) {User user1 = new User(1,"a",21);User user2 = new User(2,"b",22);User user3 = new User(3,"c",23);User user4 = new User(4,"d",24);User user5 = new User(6,"e",25);Arrays.asList(user1, user2, user3, user4, user5).stream().filter(user -> {return user.id%2==0;}).filter(user -> { return user.age>23;}).map(user -> {return user.name.toUpperCase();}).sorted((uu1,uu2)->{return uu2.compareTo(uu1);}).limit(1).forEach(System.out::print);}}//有参,无参构造,get,set,toString方法!
@Data
@NoArgsConstructor
@AllArgsConstructor
class User{int id;String name;int age;
}

14.ForkJoin

 ForkJoin

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

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

 ForkJoin的特点:工作窃取

这个里面维护的都是双端队列

ForkJoin操作:

 

package JUC.ForkJoin;import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;//测试
public class TestTime {public static void main(String[] args) throws ExecutionException, InterruptedException {test01();//385毫秒test02();//140毫秒test03();}//普通计算public static void test01(){long sum=0L;long stare = System.currentTimeMillis();for (int i = 1; i <= 10_0000_0000; i++) {sum += i;}long end = System.currentTimeMillis();System.out.println("sun="+sum+",时间为:"+(end-stare)+"毫秒");}//使用ForkJoinpublic static void test02() throws ExecutionException, InterruptedException {long stare = System.currentTimeMillis();ForkJoinPool forkJoinPool = new ForkJoinPool();TestForkJoin task = new TestForkJoin(1L, 10_0000_0000L);ForkJoinTask<Long> submit = forkJoinPool.submit(task);//提交任务Long sum = submit.get();long end = System.currentTimeMillis();System.out.println("sun="+sum+",时间为:"+(end-stare)+"毫秒");}//使用Stream流计算public static void test03(){long stare = System.currentTimeMillis();//range表示() 而rangeClosed表示(]long sum = LongStream.rangeClosed(1L, 10_0000_0000L).parallel().reduce(0, Long::sum);long end = System.currentTimeMillis();System.out.println("sun="+sum+" 时间为:"+(end-stare)+"毫秒");}
}
package JUC.ForkJoin;import java.util.concurrent.RecursiveTask;/*** 求和计算的任务** 如何使用ForkJoin?* 1.ForkJoinPool 通过它来执行* 2.计算任务 ForkJoinPool.execute(ForkJoinTask<?> task)* 3.计算类需要继承RecursiveTask抽象类*/
public class TestForkJoin extends RecursiveTask<Long> {private final Long start;//起始值  1private final Long end;//结束的值   1990999//临界值private final Long temp=1000L;public TestForkJoin(Long start, Long end) {this.start = start;this.end = end;}/*** 计算方法* @return 计算结果*/@Overrideprotected Long compute() {if ((end-start)<temp){long sum=0L;for (Long i = start; i <= end; i++) {sum+=i;}return sum;}else {//分支合并计算使用 ForkJoinlong middle = (start+end)/ 2; //中间值TestForkJoin task1 = new TestForkJoin(start, middle);task1.fork();//拆分把任务压入线程队列TestForkJoin task2 = new TestForkJoin(middle+1, end);task2.fork();//拆分把任务压入线程队列return task1.join() + task2.join();}}
}

 15.异步回调

Future设计初衷:

package JUC.Future;import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/*** 异步调用:CompletableFuture*/
public class TestCompletableFuture {public static void main(String[] args) throws ExecutionException, InterruptedException {CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(()->{System.out.println(Thread.currentThread().getName());int i = 10/0;return 1024;});//获取执行结果completableFuture.whenComplete((t,u)->{System.out.println("t->"+ t);System.out.println("u->"+u);}).exceptionally((e)->{System.out.println(e.getMessage());return 0;});}}

 16.JMM 

请你谈谈你对volatile的理解

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

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

 什么是JMM

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

关于JMM的一些同步约定:

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

 如:

package JUC.JMM;import java.util.concurrent.TimeUnit;public class TestJMM {private static boolean flag=true;public static void main(String[] args) throws InterruptedException {new Thread(()->{while (flag){}}).start();System.out.println("停顿!");TimeUnit.SECONDS.sleep(1);flag=false;System.out.println("修改完毕!");//这里直接循环卡死!}
}

 Volatile

1.保证可见性 

package JUC.JMM;import java.util.concurrent.TimeUnit;public class TestJMM {//加入volatile可以保证程序的可见性private static volatile boolean flag=true;public static void main(String[] args) throws InterruptedException {new Thread(()->{ //该线程对主内存的变化是不可见的!while (flag){}}).start();System.out.println("停顿!");TimeUnit.SECONDS.sleep(1);flag=false;System.out.println("修改完毕!");//这里直接循环卡死!}
}

2.不保证原子性

原子性:不可分割

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

package JUC.JMM;public class TestJMM02 {//volatile不保证原子性private volatile static int flag=0;public static void add(){flag++;}public static void main(String[] args) {for (int i = 0; i < 10; i++) {new Thread(()->{for (int j = 0; j < 1000; j++) {add();}}).start();}while (Thread.activeCount()>2){Thread.yield();}System.out.println(Thread.currentThread().getName()+":"+flag);}
}

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

使用原子类:

package JUC.JMM;import java.util.concurrent.atomic.AtomicInteger;public class TestJMM02 {//volatile不保证原子性private volatile static AtomicInteger flag=new AtomicInteger();public static void add(){flag.getAndIncrement();//进行+1操作}public static  void main(String[] args) {for (int i = 0; i < 10; i++) {new Thread(()->{for (int j = 0; j < 1000; j++) {add();}}).start();}while (Thread.activeCount()>2){Thread.yield();}System.out.println(Thread.currentThread().getName()+":"+flag);}
}

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

指令重排:

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

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

int x=1; //1
int y=2; //2
x=x+3;   //3
y=y*x;   //4

 我们所希望的是1234而但可能执行的时候会变成:2134,1324但不可能是4321因为处理器在进行指令重排的时候会考虑数据之间的依赖问题!

可能造成影响的结果: a,b,x.v四个值默认为0

线程A线程B
x=ay=b
b=1a=2

 正常结果:x,y都为0;但是可能由于指令重排:

线程A线程B
b=1a=2
x=ay=b

指令重排可能导致的诡异结果:x=2,y=1.

Volatile则可以避免指令重排

使其加入了内存屏障,作用:

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

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

Volatile可以保证,可见性,不保证原子性,由于内存屏障禁止了指令重排.

Volatile在单例模式下使用的最多!


http://chatgpt.dhexx.cn/article/Xl1HQJOT.shtml

相关文章

JUC详解 | JUC概述

JUC详解 | JUC概述及其基础知识准备 前言一、1. JUC概述及基础知识准备1.JUC是什么&#xff1f;2. 进程和线程3. 并行和并发4. wait/sleep的区别5.创建线程回顾6. lambda表达式6.1 什么是lambda表达式6.2 案列6.3函数式接口6.4 小结 7. synchronized回顾8. synchronized的8锁问…

juc_lock

一个不是juc一个是juc情况 class Data2{private int number 0;Lock lock new ReentrantLock();Condition condition lock.newCondition();public void increment() throws Exception{lock.lock();try {while (number ! 0){condition.await();}number ;System.out.println(T…

JUC基础(周阳老师笔记

目录 一、JMM1.volatile2.加载代码练习&#xff1a; 二、JUC基础1.什么是进程/线程&#xff0c;并发/并行进程/线程并发/并行 2.线程的状态3.线程 操作 资源类4.Lambda表达式jdk8以后的interface 5.判断/干活/通知6.防止虚假唤醒(while not if)7.标志位lock精准通知condition 8…

什么是JUC

什么是JUC JUC指的是&#xff1a;Java里的三个包 java.util.concurrentjava.util.concurrent.atomic&#xff1a;原子性java.util.concurrent.locks&#xff1a;lock锁 回顾线程和进程 进程 程序执行的一次过程&#xff0c;一个进程包含一个或多个线程。进程是资源分配的单位…

Java - JUC详解

目录 一、了解和JUC相关的概念 二、Java线程 三、线程共享模型 一、了解和JUC相关的概念 1.1 什么是JUC&#xff1f; JUC是java.util.concurrent包的简称&#xff0c;在Java5.0添加&#xff0c;目的就是为了更好的支持高并发任务。让开发者进行多线程编程时减少竞争条件和…

JUC线程池

一、JUC介绍 java.util.concurrent包&#xff08;简称&#xff1a;JUC&#xff09;。JUC主要是让开发者在多线程编程中更加简单、方便一些。 通过JDK内置了一些类、接口、关键字&#xff0c;补充完善了JDK对于并发编程支持的“短板”。 主要功能&#xff1a;&#xff08;1&am…

JUC

&#xff08;尚硅谷笔记&#xff09; Java JUC 简介  在 Java 5.0 提供了 java.util.concurrent &#xff08;简称 JUC &#xff09;包&#xff0c;在此包中增加了在并发编程中很常用 的实用工具类&#xff0c;用于定义类似于线程的自定义子 系统&#xff0c;包括线程池、异…

JUC基础知识(个人总结)

声明: 1. 本文为我的个人复习总结, 并非那种从零基础开始普及知识 内容详细全面, 言辞官方的文章 2. 由于是个人总结, 所以用最精简的话语来写文章 3. 若有错误不当之处, 请指出 一. 前置基础: IO 操作不占用 cpu, 只是我们一般拷贝文件使用的是【…

1、JUC概述

1.1 什么是JUC 在Java中&#xff0c;线程部分是一个重点&#xff0c;本篇文章说的JUC 也是关于线程的。JUC就是java.util .concurrent工具包的简称。这是一个处理线程的工具包&#xff0c;JDK1.5开始出现的。 1.2 线程和进程的概念 进程和线程 进程&#xff08;Process&…

JUC基础【万字篇】

JUC 1、什么是JUC JUC&#xff1a;指的是java.util三个并发编程工具包 java.util.concurrentjava.util.concurrent.atomicjava.util.concurrent.locks 实现多线程的四种方式&#xff1a; 继承Thread类实现Runnable接口实现Callable接口线程池 业务&#xff1a;普通的线程代…

java--JUC快速入门(彻底搞懂JUC)

java–JUC快速入门&#xff08;彻底搞懂JUC&#xff09; 文章目录 java--JUC快速入门&#xff08;彻底搞懂JUC&#xff09;1、学习多线程之前需要知道的一些概念。2、JUC的结构3、Lock锁(重点)4、集合类不安全5、Callable()6、常用的辅助类7、读写锁8、阻塞队列9、线程池 1、学…

Dbeaver做数据迁移

1、选择源头数据库的表、鼠标右击、选择导出数据 2、在数据转化弹框中&#xff0c;双击 ‘数据库&#xff0c;数据表’ 那一栏 3、选择目标数据库&#xff0c;调整字段类型映射关系 4、调整字段的映射关系 目前遇到的字段类型&#xff0c;只有 int&#xff0c;bigint 转 num…

dbeaver工具连接达梦数据库

、一 概述 DBeaver 是一个基于 Java 开发&#xff0c;免费开源的通用数据库管理和开发&#xff0c;DBeaver 采用 Eclipse 框架开发&#xff0c;支持插件扩展&#xff0c;并且提供了许多数据库管理工具&#xff1a;ER 图、数据导入/导出、数据库比较、模拟数据生成等&#xff0…

DBeaver 格式化sql

有时候我们拿到了一条sql语句是长长的&#xff0c;非常不容易阅读&#xff0c;这时我们就想说哪里可以格式下sql代码。 方法有很多种&#xff0c;这里我就用Dbeaver来格式化sql。 ①打开Dbeaver ②复制sql代码到SQL编辑器中&#xff0c;并选中 ③按ctrlshiftF&#xff0c;即…

【DBeaver】常用自定义设置

文章目录 背景一、用户界面设置1.1、22.3.4版本1.1.1、SQL编辑器-字体设置1.1.2、查询结果-字体设置 1.2、23.0.0版本1.2.1、应用字体&#xff08;导航栏等&#xff09;1.2.2、文本字体&#xff08;SQL输出、文本编辑器等&#xff09; 二、常规设置2.1、连接类型设置/环境设置 …

DBeaver导入Excel数据

目录 前言 导入准备 ​导入步骤 1.选中数据库表&#xff0c;右键&#xff0c;然后点击导入数据 2.双击CSV,选择待导入的文件 3.修改编码格式&#xff08;可选&#xff0c;不乱码不用&#xff09; 4.点击下一步&#xff0c;修改列的类型 5.一直下一步&#xff0c;点击…

Dbeaver基本使用

1&#xff1a;与plsql相比&#xff0c;Dbeaver没有右击直接查看表注释的功能&#xff0c;但是Dbeaver提供了一个“打开声明”的功能&#xff0c;里面可以查看一些比较实用的内容&#xff1a;表列注释、创建该表的create语句&#xff1a; 2&#xff1a;在一般开发的情况下&#…

【大数据】Hive可视化工具dbeaver

Hive可视化工具dbeaver 1、dbeaver基本介绍 dbeaver是一个图形化的界面工具&#xff0c;专门用于与各种数据库的集成&#xff0c;通过dbeaver我们可以与各种数据库进行集成通过图形化界面的方式来操作我们的数据库与数据库表&#xff0c;类似于我们的sqlyog或者navicat。 2、…

DBeaver安装及使用手册

一、DBeaver安装 1、在[DBeaver官网](https://dbeaver.io/download)进行数据库工具下载&#xff0c;下载好后双击运行2、选择语言后&#xff0c;点击OK 3、点击下一步 4、接受许可 5、选择可使用者&#xff0c;然后点击下一步 6、选择组件&#xff0c;一般选择默认即可 7…

DBeaver-Driver-All ( DBeaver驱动包,所有JDBC驱动整合包)

DBeaver-Driver-All DBeaver-Driver-All ( DBeaver驱动包 )整合所有DBeaver的JDBC驱动包&#xff0c;供DBeaver使用&#xff0c;无需每次都搜索和下载&#xff0c;只需clone本项目即可&#xff0c;一个包包含几乎所有的驱动&#xff0c;如果有缺漏的驱动欢迎提Issue补充。 DBe…