注:该笔记主要记录自 B站 up主 遇见狂神说的个人空间_哔哩哔哩_bilibili
1、什么是 JUC
Java 工具类中的 并发编程包
学习:源码 + 官方文档
业务:普通的线程代码 Thread
Runnable 没有返回值、效率相比于 Callable 相对较低!
2、线程和进程
进程:程序运行的实例
一个进程至少包含一个线程,可以包括多个线程
Java 默认有几个线程?2 个 main、GC
线程:开了一个进程 Typora,写字、自动保存 由线程负责
对于 Java 而言:Thread、Runnable、Callable
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
// 本地方法,底层是 C++,Java 无法直接操作硬件
private native void start0();
并发、并行的区别
并发(多线程操作同一个资源)
- CPU 单核,模拟出多条线程,线程切换快速交替
并行(多个人一起行走)
- CPU 多核,多个线程可以同时执行;线程池
package com.fengluo.demo01;
public class Test1 {
public static void main(String[] args) {
// 获取 CPU 的核数
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
并发编程的本质:充分利用 CPU 的资源!
线程有几个状态?
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 区别:
-
来自不同的类
- wait -》Object
- sleep -》Thread
-
关于锁的释放
- wait 会释放锁;sleep 睡觉了,抱着锁睡觉,不会释放锁!(狂神讲的也太通俗了hhh)
-
使用的范围不同
- wait 必须在同步代码块中使用
- sleep 可以在任何地方睡
-
是否需要捕获异常
- wait 不需要捕获异常
- sleep 必须要捕获异常
3、Lock 锁(重点)
传统的 synchronized
synchronized 四个特性
- 原子性,与 volatile 的区别,volatile 没有原子性
- 所谓原子性就是指一个操作或者多个操作,要么全部执行并且执行的过程不会被任何因素打断,要么就都不执行
- 可见性
- 可见性是指多个线程访问一个资源时,该资源的状态、值信息等对于其他线程都是可见的
- 有序性
- 有序性指程序执行的顺序按照代码先后执行。
- 可重入性
- 通俗一点讲就是说一个线程拥有了锁仍然还可以重复申请锁
它的可以修饰静态方法、成员函数,同时可以定义代码块。总之,锁的资源只有两个,对象,类。
package com.fengluo.demo01;
/**
* 线程就是一个单独的资源类,没有任何的附属的操作!
*/
public class SaleTicketDemo01 {
public static void main(String[] args) {
// 并发:多线程操作一个资源类,把资源类丢入线程
Ticket ticket = new Ticket();
// @函数式接口
new Thread(()->{
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}, "A").start();
new Thread(()->{
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}, "B").start();
new Thread(()->{
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}, "C").start();
}
}
// 资源类,属性 + 方法,面向对象思想
class Ticket {
private int number = 50;
// synchronized
public synchronized void sale() {
if (number > 0) {
System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票, 剩余" + number);
}
}
}
Lock 接口
公平锁:先来后到,公平分配
非公平锁:可以插队(默认非公平锁,是为了总体的公平)
package com.fengluo.demo01;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 线程就是一个单独的资源类,没有任何的附属的操作!
*/
public class SaleTicketDemo02 {
public static void main(String[] args) {
// 并发:多线程操作一个资源类,把资源类丢入线程
Ticket2 ticket = new Ticket2();
// @函数式接口
new Thread(()->{for (int i = 0; i < 40; i++) ticket.sale();}, "A").start();
new Thread(()->{for (int i = 0; i < 40; i++) ticket.sale();}, "B").start();
new Thread(()->{for (int i = 0; i < 40; i++) ticket.sale();}, "C").start();
}
}
// Lock
// new 锁对象
// 加锁
// 解锁
class Ticket2 {
private int number = 50;
Lock lock = new ReentrantLock();
public synchronized void sale() {
lock.lock();
try {
// 业务代码
if (number > 0) {
System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票, 剩余" + number);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
Synchronized 和 lock 的区别
1、Synchronized 是内置 Java 关键字,Lock 是一个类
2、Synchronized 无法判断获取锁的状态,Lock 可以判断是否获取到了锁
3、Synchronized 会自动释放,Lock 必须要手动释放锁,否则可能导致死锁
4、Synchronized 线程1(获得锁,阻塞)线程2(等待,傻等);Lock 锁可以尝试获取锁
5、Synchronized 可重入锁,不可以中断,非公平;Lock 可重入锁,可以判断锁,可以自定义公平锁
6、Synchronized 适合锁少量的代码同步问题,Lock 适合锁大量的同步代码
4、生产者和消费者问题
Synchronized 方式
package com.fengluo.pc;
/**
* 线程之间的通信问题
* 线程交替问题 A B
*/
public class A {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
}
}
class Data {// 数字 资源类
private int number = 0;
// +1
public synchronized void increment() throws InterruptedException {
if (number != 0) {
// 等待
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,我 +1 完毕了
this.notifyAll();
}
// -1
public synchronized void decrement() throws InterruptedException {
if (number == 0) {
// 等待
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,我 -1 完毕了
this.notifyAll();
}
}
以上,存在问题,如果有四个线程或者多个线程存在,则会产生虚假唤醒的问题
要解决以上问题,需要将 判断条件的 if 转为 while
JUC 版的生产者消费者问题
代码实现:
package com.fengluo.pc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 线程之间的通信问题
* 线程交替问题 A B
*/
public class B {
public static void main(String[] args) {
Data2 data = new Data2();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "C").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "D").start();
}
}
class Data2 {// 数字 资源类
private int number = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
// +1
public void increment() throws InterruptedException {
try {
lock.lock();
while (number != 0) {
// 等待
condition.await();
}
number++;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,我 +1 完毕了
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
// -1
public void decrement() throws InterruptedException {
try {
lock.lock();
while (number == 0) {
// 等待
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,我 -1 完毕了
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
问题:随机状态;如何让四个线程达到有序执行?
Conditional
任何一个新技术,一定都是有优势或补充!
Conditional 可以精准的唤醒每个线程
package com.fengluo.pc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class C {
public static void main(String[] args) {
Data3 data3 = new Data3();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data3.printA();
}
}, "A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data3.printB();
}
}, "B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data3.printC();
}
}, "C").start();
}
}
// 资源锁
class Data3 {
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
private int num = 1;
public void printA() {
try {
lock.lock();
while (num != 1) {
// 等待
condition1.await();
}
System.out.println(Thread.currentThread().getName() + "=> AAAAAA");
// 唤醒 B
num++;
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB() {
try {
lock.lock();
while (num != 2) {
// 等待
condition2.await();
}
System.out.println(Thread.currentThread().getName() + "=> BBBBBB");
// 唤醒 C
num++;
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC() {
try {
lock.lock();
while (num != 3) {
// 等待
condition3.await();
}
System.out.println(Thread.currentThread().getName() + "=> CCCCCC");
// 唤醒 A
num = 1;
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
可以达到多个线程的精准唤醒,已达到顺序执行
5、八锁现象
package com.fengluo.lock8;
import java.util.concurrent.TimeUnit;
/**
* 八锁 就是 关于锁的 八个问题
* 1. 因为有锁的存在
*/
public class Test1 {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(()->{
phone.sendSms();
}, "A").start();
// 捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone.call();
}, "B").start();
}
}
class Phone {
// 锁的 对象就是方法的调用者!
// 两个方法用的是同一个锁,谁先拿到锁,谁就能执行
public synchronized void sendSms() {
// 捕获
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
}
package com.fengluo.lock8;
import java.util.concurrent.TimeUnit;
/**
* 八锁 就是 关于锁的 八个问题
* 1. 因为有锁的存在
*
* 3.增加一个普通方法,先执行那个方法
* 4.两个对象。两个手机!
*/
public class Test2 {
public static void main(String[] args) {
Phone2 phone1 = new Phone2();
Phone2 phone2 = new Phone2();
new Thread(()->{
phone1.sendSms();
}, "A").start();
// 捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
}, "B").start();
}
}
class Phone2 {
// 锁的 对象就是方法的调用者!
// 两个方法用的是同一个锁,谁先拿到锁,谁就能执行
public synchronized void sendSms() {
// 捕获
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
public void hello() {
System.out.println("Hello!");
}
}
package com.fengluo.lock8;
import java.util.concurrent.TimeUnit;
/**
* 八锁 就是 关于锁的 八个问题
* 1. 因为有锁的存在
*
* 3.增加一个普通方法,先执行那个方法
* 4.两个对象。两个手机!
*/
public class Test3 {
public static void main(String[] args) {
Phone3 phone1 = new Phone3();
Phone3 phone2 = new Phone3();
new Thread(()->{
phone1.sendSms();
}, "A").start();
// 捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
}, "B").start();
}
}
class Phone3 {
// 锁的 对象就是方法的调用者!
// 两个方法用的是同一个锁,谁先拿到锁,谁就能执行
// static 是静态方法,类一加载就有了,Class
public static synchronized void sendSms() {
// 捕获
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public static synchronized void call() {
System.out.println("打电话");
}
}
package com.fengluo.lock8;
import java.util.concurrent.TimeUnit;
/**
* 八锁 就是 关于锁的 八个问题
* 1. 因为有锁的存在
*
* 3.增加一个普通方法,先执行那个方法
* 4.两个对象。两个手机!
*/
public class Test4 {
public static void main(String[] args) {
Phone4 phone1 = new Phone4();
Phone4 phone2 = new Phone4();
new Thread(()->{
phone1.sendSms();
}, "A").start();
// 捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
}, "B").start();
}
}
class Phone4 {
// 锁 Class
public static synchronized void sendSms() {
// 捕获
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
// 锁 对象
public synchronized void call() {
System.out.println("打电话");
}
}
小结
new this 是一个具体的对象
static Class 是一个唯一的模板
6、集合类不安全
List 不安全,vector 安全但是效率低
package com.fengluo.unsafe;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
// ConcurrentModifiedException 并发修改异常
public class ListTest {
/**
* 解决办法:1. 使用 Vector,Vector jdk 1.0 就出现了。List 集合 1.2 才出现,Vetctor 的add 是线程安全的方法,但是 synchronized 的性能差
* 2. Collections.synchronized***
* 3. CopyOnWrite
**/
public static void main(String[] args) {
// CopyOnWrite
// 多个线程调用的时候,list 读取的时候是固定的
// 在写入时 避免覆盖,造成数据问题!
// 读写问题
// CopyOnWrite 使用 lock
// Vector 使用 synchronized
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10; i++) {
new Thread(()->{
list.add((UUID.randomUUID().toString().substring(0, 5)));
System.out.println(list);
}, String.valueOf(i)).start();
}
}
}
Set
package com.fengluo.unsafe;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
public class SetTest {
public static void main(String[] args) {
// java.util.ConcurrentModificationException
// 1. Collections.synchronizedSet(new HashSet<>());
// 2. new CopyOnWriteArraySet<>();
Set<String> set = new CopyOnWriteArraySet<>();
for (int i = 0; i < 50; i++) {
new Thread(()->{
set.add((UUID.randomUUID().toString().substring(0, 5)));
System.out.println(set);
},String.valueOf(i)).start();
}
}
}
HashSet 的底层是什么?
public HashSet() {
map = new HashMap<>();
}
// add set 本质 就是 map key 是无法重复的
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
Map 不安全
package com.fengluo.unsafe;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Handler;
public class MapTest {
public static void main(String[] args) {
// map
Map<String, Object> map = new ConcurrentHashMap<>();
// 加载因子、初始化容量
for (int i = 0; i < 30; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), (UUID.randomUUID().toString().substring(0, 5)));
System.out.println(map);
}, String.valueOf(i)).start();
}
}
}
7、Callable
1、可以有返回值
2、可以抛出异常
3、方法不同,run 和 call,通过 FutureTask 适配 Thread
package com.fengluo.callable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
new Thread().start(); // 怎么启动 Callable
MyThread myThread = new MyThread();
// 适配类
FutureTask futureTask = new FutureTask(myThread);
new Thread(futureTask, "A").start();
new Thread(futureTask, "B").start();
Integer o = (Integer) futureTask.get(); // 这个 get 方法可能会产生阻塞,要放到最后
// 或者使用异步通信来处理 !
System.out.println(o);
}
}
class MyThread implements Callable<Integer> {
@Override
public Integer call() {
System.out.println("Call()"); // 多个线程, 会打印几个 call?
// 耗时的操作
return 1651;
}
}
细节
1、有缓存
2、结果可能阻塞,需要等待!
8、常用的辅助类(AQS同步框架)(高并发)
8.1、CountDownLatch
package com.fengluo.add;
import java.util.concurrent.CountDownLatch;
// 计数器
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
// 总数是 6, 必须要执行某一项任务时,在使用
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName() + " Go out ");
countDownLatch.countDown();
}, String.valueOf(i)).start();
}
countDownLatch.await(); // 等待计数器归零,才继续执行
System.out.println("close door");
}
}
原理:
countDownLatch.countDown(); // 数量 - 1
countDownLatch.await(); // 等待计数器归零,然后再继续执行
每次有线程调用 countDown() 数量 - 1,假设计数器变为0,countDownLatch.await() 就会被唤醒,继续执行!
8.2、CyclicBarrier
加法计数器
package com.fengluo.add;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String[] args) {
/**
* 集齐 7 颗龙珠召唤神龙
*/
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, ()->{
System.out.println("召唤神龙成功!");
});
for (int i = 0; i < 7; i++) {
final int temp = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "收集第" + temp + "颗龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
8.3、Semaphore
抢车位!
package com.fengluo.add;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
// 线程数量:停车位
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 6; 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();
}
}, String.valueOf(i)).start();
}
}
}
原理:
semaphore.acquire(); // 获得,假设已经满了,等待,等到资源被释放为止
semaphore.release(); // 释放,会将当前的信号量释放 +1,然后唤醒等待的线程!
作用:多个共享资源互斥的使用!并发限流,控制最大的线程数!
9、读写锁
可以被多个线程读,但是只能被一个线程写!
独占锁(写锁)一次只能被一个线程占有
共享锁(读锁)多个线程可以同时占有
package com.fengluo.rw;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCacheLock myCache = new MyCacheLock();
// 写入
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(()->{
myCache.put(temp+"", temp+"");
}, String.valueOf(i)).start();
}
// 读取
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(()->{
myCache.get(temp+"");
}, String.valueOf(i)).start();
}
}
}
/**
* 自定义缓存
*/
class MyCacheLock {
private volatile Map<String, Object> map = new HashMap<>();
private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
// 存,写,写入的时候只希望同时仅有一个线程写
public void put(String key, Object value) {
reentrantReadWriteLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "写入" + key);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "写入 OK");
} catch (Exception e) {
e.printStackTrace();
} finally {
reentrantReadWriteLock.writeLock().unlock();
}
}
// 取,读,所有人都可以读
public void get(String key) {
reentrantReadWriteLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "读取" + key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName() + "读取OK");
} catch (Exception e) {
e.printStackTrace();
} finally {
reentrantReadWriteLock.readLock().unlock();
}
}
}
class MyCache{
private volatile Map<String, Object> map = new HashMap<>();
// 存,写
public void put(String key, Object value) {
System.out.println(Thread.currentThread().getName() + "写入" + key);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "写入 OK");
}
// 取,读
public void get(String key) {
System.out.println(Thread.currentThread().getName() + "读取" + key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName() + "读取OK");
}
}
10、阻塞队列
不得不阻塞
写入:如果队列满了,就必须阻塞等待
取:如果队列时空的,就必须等待生产
BlockingQueue 什么情况下会使用?
- 线程池
学会使用队列
四组 API
1、抛出异常
2、不抛出异常
3、阻塞等待
4、超时等待
方式 | 抛出异常 | 不抛出异常 | 阻塞等待 | 超时等待 |
---|---|---|---|---|
添加 | add | offer | put | offer(,) |
移除 | remove | poll | take | poll(,) |
获取队首 | element | peek |
package com.fengluo.bq;
import java.util.Collection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
test4();
}
// 抛出异常
public static void test1() {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
//System.out.println(blockingQueue.add("d"));
System.out.println(blockingQueue.element());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
// java.util.NoSuchElementException 抛出异常
System.out.println(blockingQueue.remove());
}
// 有返回值,不抛出异常
public static void test2() {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
System.out.println(blockingQueue.offer("d"));
System.out.println(blockingQueue.peek());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
}
// 等待,一直阻塞(一直阻塞)
public static void test3() throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
//blockingQueue.put("d");
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
}
// 等待,阻塞(等待超时)
public static void test4() throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.offer("a");
blockingQueue.offer("b");
blockingQueue.offer("c");
//blockingQueue.offer("d", 2, TimeUnit.SECONDS);
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
}
}
SynchronizedQueue 同步队列
没有容量,不存储元素,进去一个元素,必须等待取出来之后,才能再往里面放一个原则!
put、take
package com.fengluo.bq;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
public class SynchronizedQueueDemo {
public static void main(String[] args) {
BlockingQueue<String> synchronizedQueue = new SynchronousQueue<>(); // 同步队列
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName() + "put 1");
synchronizedQueue.put("1");
System.out.println(Thread.currentThread().getName() + "put 2");
synchronizedQueue.put("2");
System.out.println(Thread.currentThread().getName() + "put 3");
synchronizedQueue.put("3");
} catch (Exception e) {
e.printStackTrace();
}
}, "T1").start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + "=>" + synchronizedQueue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + "=>" + synchronizedQueue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + "=>" + synchronizedQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "T2").start();
}
}
11、线程池(重点)
线程池:三大方法、七大参数、四种拒绝策略
池化技术
程序的运行,本质:占用系统的资源!
为了优化资源的使用!=》池化技术
池化技术:事先准备好一些资源,有人要用就来我这里拿,用完之后归还即可。
线程池的好处
1、降低系统资源的消耗
2、提高系统的响应速度
3、方便管理
线程复用、可以控制最大并发数、管理线程
线程池 三大方法
package com.fengluo.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// Executor 工具类, 三大方法
// 使用了线程池之后,需要使用线程池来创建线程
public class Demo01 {
public static void main(String[] args) {
// ExecutorService threadPool = Executors.newSingleThreadExecutor();// 单个线程
// ExecutorService threadPool = Executors.newFixedThreadPool(5);// 创建一个固定的线程池的大小
ExecutorService threadPool = Executors.newCachedThreadPool();// 遇强则强,遇弱则弱
// 线程池用完,程序结束,关闭线程池
try {
for (int i = 0; i < 100; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+" ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
}
线程池 七大参数
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,
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.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
线程池 四种拒绝策略
AbortPolicy() // 阻塞队列满了,不处理,抛异常
CallerRunsPolicy() // 哪里来的去哪里,打发了
DiscardPolicy() // 队列满了,丢掉任务,不会抛出异常
DiscardOldestPolicy() // 队列满了,尝试和最早的竞争
小结和拓展
最大线程到底如何定义?
1.CPU 密集型,几核,就是几,可以保持 CPU 的效率最高
2.IO 密集型 判断你程序中十分耗 IO 的线程
// 获取 CPU 的核数
System.out.println(Runtime.getRuntime().availableProcessors());
12、四大函数式接口(必须掌握)
新时代的程序员:lambda 表达式、链式编程、函数式接口、Stream 流式计算
函数式接口:只有一个方法的接口,用来简化编程模型
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
// @FunctionalInterface 超级多
// 简化编程模型,在新版本的框架底层大量应用!
// foreach(消费者类的函数式接口)
代码测试:
Function 函数式接口
package com.fengluo.function;
import java.util.function.Function;
/**
* function 函数型接口,有一个输入参数,有一个输出
* 只要是函数性接口,可以用 lambda 表达式简化
*/
public class Demo {
public static void main(String[] args) {
Function<String, String> function = new Function<String, String>() {
@Override
public String apply(String s) {
return s;
}
};
System.out.println(function.apply("as"));
Function function1 = (str) -> {
return str;
};
System.out.println(function1.apply("fxck"));
}
}
Predicate 断定型接口,有一个输入参数,返回值只能是 布尔值!
package com.fengluo.function;
import java.util.function.Predicate;
public class Demo02 {
public static void main(String[] args) {
// 判断字符串是否为空
Predicate<String> predicate = new Predicate<String>() {
@Override
public boolean test(String str) {
return str.isEmpty();
}
};
System.out.println(predicate.test(""));
Predicate<String> predicate1 = (str) -> {return str.isEmpty();};
System.out.println(predicate1.test("ds"));
}
}
Consumer 消费型接口,只有输入,没有返回值
package com.fengluo.function;
import java.util.function.Consumer;
public class Demo3 {
public static void main(String[] args) {
Consumer<String> consumer = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
Consumer<String> consumer1 = (str) -> {
System.out.println(str);
};
consumer1.accept("dwad");
}
}
Supplier 供给型接口,没有参数,只有返回值
package com.fengluo.function;
import java.util.function.Supplier;
public class Demo04 {
public static void main(String[] args) {
Supplier supplier = new Supplier() {
@Override
public Object get() {
return 1024;
}
};
Supplier supplier1 = () -> {
return 1024;
};
System.out.println(supplier1.get());
}
}
13、Stream 流式计算
什么是 Stream 流式计算
大数据:存储 + 计算
存储,集合、MySQL,本质就是存储东西的
计算都应该交给流来操作!
流式计算通过结合 函数式编程以及 lambda 表达式 来实现对 数据的操作!
14、ForkJoin
什么是 ForkJoin
在 JDK1.7,并行执行任务!提高效率,大数据量!
把大任务分为子任务,最终将子任务的处理结果合并成最终结果
ForkJoin 特点:工作窃取!切分执行!结果合并!
package com.fengluo.forkjoin;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
test3();
}
public static void test1() {
Long start = System.currentTimeMillis();
Long sum = 0L;
for (Long i = 0L; i < 10_0000_0000; i++) {
sum += i;
}
Long end = System.currentTimeMillis();
System.out.println(sum + " " + (end - start));
}
public static void test2() throws ExecutionException, InterruptedException {
Long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long> task = new ForkJoinDemo(0L, 10_0000_0000L);
ForkJoinTask<Long> submit = forkJoinPool.submit(task);
Long sum = submit.get();
Long end = System.currentTimeMillis();
System.out.println(sum + " " + (end - start));
}
public static void test3() {
Long start = System.currentTimeMillis();
// Steam 并行流
long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
Long end = System.currentTimeMillis();
System.out.println(sum + " " + (end - start));
}
}
15、异步回调
package com.fengluo.future;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* 异步调用: CompletableFuture
* 1. 异步执行
* 2. 成功回调
* 3. 失败回调
*/
public class Demo0 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 无返回值的异步回调
//CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(()->{
// try {
// TimeUnit.SECONDS.sleep(0);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName()+"runAsync => Void");
//});
//
//System.out.println("先拿到");
//voidCompletableFuture.get();
//System.out.println("后拿到");
//
CompletableFuture<Integer> objectCompletableFuture = CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread().getName()+"supplyAsync => Integer");
return 1024;
});
System.out.println(objectCompletableFuture.whenComplete((t, u)->{
System.out.println("t=>" + t);
System.out.println("u=>" + u);
}).exceptionally((e)->{
System.out.println(e.getMessage());
return 2333;
}).get());
}
}
没太听懂,大概的理解就是。。。执行代码时,有个步骤需要处理等待五秒,我们不想等这个五秒,直接异步继续执行后面的代码,然后等这个步骤的五秒处理完了,我们再回调取到返回的值。。。大概就是异步回调了。
16、JMM
请你谈谈你对 volatile 的理解?
volatile 是 Java 虚拟机提供的轻量级的同步机制
1、保证可见性(每个工作线程都有自己的工作内存,所以当某个线程修改完某个变量之后,在其他的线程中,未必能观察到该变量已经被修改。volatile关键字要求被修改之后的变量要求立即更新到主内存,每次使用前从主内存处进行读取。因此volatile可以保证可见性。除了volatile以外,synchronized和final也能实现可见性。synchronized保证unlock之前必须先把变量刷新回主内存。final修饰的字段在构造器中一旦完成初始化,并且构造器没有this逸出,那么其他线程就能看到final字段的值。)
2、不保证原子性(例如 JMM 八项操作,在操作系统里面是不可分割的单元。被synchronized关键字或其他锁包裹起来的操作也可以认为是原子的。从一个线程观察另外一个线程的时候,看到的都是一个个原子性的操作。)
3、禁止指令重排,保证有序性 (java的有序性跟线程相关。如果在线程内部观察,会发现当前线程的一切操作都是有序的。如果在线程的外部来观察的话,会发现线程的所有操作都是无序的。因为JMM的工作内存和主内存之间存在延迟,而且java会对一些指令进行重新排序。volatile和synchronized可以保证程序的有序性,很多程序员只理解这两个关键字的执行互斥,而没有很好的理解到volatile和synchronized也能保证指令不进行重排序。)
什么是 JMM?
JMM 是 Java 内存模型,不存在的东西,是一个概念,一种约定!JMM即为JAVA 内存模型(java memory model)。因为在不同的硬件生产商和不同的操作系统下,内存的访问逻辑有一定的差异,结果就是当你的代码在某个系统环境下运行良好,并且线程安全,但是换了个系统就出现各种问题。Java内存模型,就是为了屏蔽系统和硬件的差异,让一套代码在不同平台下能到达相同的访问结果。
关于 JMM 的一些同步的约定:
1、线程解锁前,必须把共享变量立刻刷回主存
2、线程加锁前,必须读取主存中的最新值到工作内存中!
3、加锁和解锁是同一把锁!
内存划分
JMM规定了内存主要划分为主内存和工作内存两种。此处的主内存和工作内存跟JVM内存划分(堆、栈、方法区)是在不同的层次上进行的,如果非要对应起来,主内存对应的是Java堆中的对象实例部分,工作内存对应的是栈中的部分区域,从更底层的来说,主内存对应的是硬件的物理内存,工作内存对应的是寄存器和高速缓存。
JVM在设计时候考虑到,如果JAVA线程每次读取和写入变量都直接操作主内存,对性能影响比较大,所以每条线程拥有各自的工作内存,工作内存中的变量是主内存中的一份拷贝,线程对变量的读取和写入,直接在工作内存中操作,而不能直接去操作主内存中的变量。但是这样就会出现一个问题,当一个线程修改了自己工作内存中变量,对其他线程是不可见的,会导致线程不安全的问题。因为JMM制定了一套标准来保证开发者在编写多线程程序的时候,能够控制什么时候内存会被同步给其他线程。
这里狂神的 write 和 store 写反了。
内存交互操作
内存交互操作有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操作之前,必须把此变量同步回主内存
17、Volatile
三个特性
-
1、保证可见性
-
2、不保证原子性
-
3、禁止指令重排,保证有序性
可见性补充:
- volatile保证了修饰的共享变量在转换为汇编语言时,会加上一个以lock为前缀的指令,当CPU发现这个指令时,立即会做两件事情:
- 将当前内核中线程工作内存中该共享变量刷新到主存;
- 通知其他内核里缓存的该共享变量内存地址无效;
当且仅当满足以下条件下,才应该使用volatile变量:
1、对变量的写入操作不依赖变量的当前值,或者确保只有单个线程变更变量的值。
2、该变量不会于其他状态一起纳入不变性条件中
3、在访问变量的时候不需要加锁。
可见性,测试
package com.fengluo.tvolatile;
import java.util.concurrent.TimeUnit;
public class JMMDemo {
private static volatile int num = 0;
public static void main(String[] args) {
new Thread(()->{
while (num == 0) {
}
}).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
num = 1;
System.out.println(num);
}
}
不保证原子性,测试
原子性:不可分割,要么同时成功,要么同时失败。
package com.fengluo.tvolatile;
public class VDemo02 {
private static int num = 0;
public static void add() {
num++;
}
public static void main(String[] args) {
// 理论上 num 结果应为 2万
for (int i = 0; i < 20; i++) {
new Thread(()->{
for (int i1 = 0; i1 < 1000; i1++) {
add();
}
}).start();
}
while (Thread.activeCount() > 2) { // main gc
Thread.yield();
}
System.out.println(Thread.currentThread().getName()+"->" + num);
}
}
如果 不使用 synchronized 和 lock 怎么保证原子性?(使用原子类)
原子类为什么这么高级?(CAS)
package com.fengluo.tvolatile;
import java.util.concurrent.atomic.AtomicInteger;
public class VDemo02 {
private volatile static AtomicInteger num = new AtomicInteger();
public static void add() {
//num++; // 不是一个原子性操作
num.getAndIncrement(); // AtomicInteger + 1 方法,CAS
}
public static void main(String[] args) {
// 理论上 num 结果应为 2万
for (int i = 0; i < 20; i++) {
new Thread(()->{
for (int i1 = 0; i1 < 1000; i1++) {
add();
}
}).start();
}
while (Thread.activeCount() > 2) { // main gc
Thread.yield();
}
System.out.println(Thread.currentThread().getName()+"->" + num);
}
}
这些类的底层都是直接和操作系统挂钩!在内存中修改值!Unsafe 类是一个很特殊的存在!
什么是指令重排?
你写的程序,计算机只保证结果是程序的结果,但可能并不是按照你写的那样去执行的!
源代码 --> 编译器优化的重排 --> 指令并行可能也会重排 --> 内存系统也会重排 --> 执行
处理器在进行指令重排的时候,会考虑数据之间的依赖性!
被volatile修饰的变量,会加一个lock前缀的汇编指令。若变量被修改后,会立刻将变量由工作内存回写到主存中。那么意味了之前的操作已经执行完毕
。这就是内存屏障。
小结:volatile 保证可见性, 不能保证原子性,由于内存屏障,可以保证避免指令重排的现象产生。
18、彻底玩转单例模式
单例模式笔者已经总结学习过了,这里就看了下视频没有做笔记。。可以看我的单例模式博客
【无脑速通设计模式】单例模式_Java攻城狮修炼中-CSDN博客
19、深入理解 CAS
Unsafe 类
比较当前工作内存中的值和主内存中的值,如如果这个值是期望的,那么执行操作,如果不是就一直循环!
缺点:
1、自旋锁,循环会耗时
2、一次性只能保证一个共享变量的原子性
3、存在 ABA 问题
CAS:ABA 问题(狸猫换太子)
左边不知道拿到的数据 A 实际上已经被 右边修改过了。
package com.fengluo.cas;
import java.util.concurrent.atomic.AtomicInteger;
public class CASDemo {
// CAS,compareAndSet:比较并交换
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(2020);
// 对于我们平时写的SQL: 乐观锁!
// 期望、更新
// 如果我期望的值拿到了,那么就更新,否则,就不更新
// ================ 捣乱线程 ===============
System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get());
System.out.println(atomicInteger.compareAndSet(2021, 2020));
System.out.println(atomicInteger.get());
// CAS 是 CPU 的原语! =================
System.out.println(atomicInteger.compareAndSet(2020, 6666));
System.out.println(atomicInteger.get());
}
}
20、原子引用
解决 ABA 问题,引入原子引用,乐观锁
package com.fengluo.cas;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;
public class CASDemo {
// CAS,compareAndSet:比较并交换
public static void main(String[] args) {
// 乐观锁
//AtomicInteger atomicInteger = new AtomicInteger(2020);
AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(1, 1);
new Thread(()->{
int stamp = atomicInteger.getStamp();
System.out.println("a1=>" + stamp);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(atomicInteger.compareAndSet(1, 2, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));
System.out.println("a2=>" + atomicInteger.getStamp());
System.out.println(atomicInteger.compareAndSet(2, 1, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));
System.out.println("a3=>" + atomicInteger.getStamp());
}, "A").start();
new Thread(()->{
int stamp = atomicInteger.getStamp();
System.out.println("b1=>" + stamp);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(atomicInteger.compareAndSet(1, 6, stamp, stamp + 1));
System.out.println("b2=>" + atomicInteger.getStamp());
}, "B").start();
}
}
带版本号的原子操作!
Integer 使用了对象缓存机制,默认范围是 -128~127,推荐使用静态工厂方法 valueOf 获取对象实例,而不是 new ,因为 valueOf 使用缓存,而 new 一定会创建新的分配对象分配新的内存空间!
21、各种锁的理解
这里觉得可以自己下去补一补,没有记笔记了,Java锁机制需要好好掌握
1、公平锁、非公平锁
公平锁:非常公平,不能插队,必须先来后到!
非公平锁:非常不公平,可以插队!(默认都是非公平锁)
ReentrantLock() 默认非公平锁
2、可重入锁
可重入锁(递归锁)
3、自旋锁
spinlock
22、死锁
形成死锁 的 四个必要条件
1、互斥性
2、保持和等待
3、不可抢占
4、循环等待
解决死锁的办法
1、使用 jps -l 定位进程号
2、使用 jstack 进程号 找到死锁
found 1 deadlock
面试,要求排查问题:
1、查看日志
2、堆栈信息