Future设计的初衷:对异步线程的返回结果进行建模。通俗的讲类似于ajax,当异步线程返回的结果是A的时候该如何,返回B又该如何。
public static void main(String[] args) throws ExecutionException, InterruptedException {
//没有返回值的 runAsync 异步回调
/*CompletableFuture completableFuture = CompletableFuture.runAsync(() ->{
System.out.println(Thread.currentThread().getName()+"ok");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("11111111111111");
completableFuture.get();*/
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() ->{
try {
int result = 10/0;
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1024;
});
System.out.println("11111111111111");
completableFuture.whenComplete((u,t) ->{//异步线程成功执行完成,并返回结果
System.out.println("u======>"+u);
System.out.println("t======>"+t);
}).exceptionally((e) ->{//异步线程执行过程中报错
System.out.println("exceptionally"+e.getMessage());
return 2333;
});
}
什么是JMM
? java内存模型,是一种约定,或则说是一个概念。它规定了java中主内存和线程内存之间的关系,具体如下图所示:
? 如上图所示,内存交互经历了8个操作:
JMM 对这八种指令的使用,制定了如下规则:
问题: 程序不知道主内存的值已经被修改过了
public class Demo1 {
volatile static boolean flag = false;
public static void main(String[] args) {
new Thread( () ->{
System.out.println("线程开始");
while(!flag){
}
System.out.println("线程结束");
}).start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = true;
System.out.println("已经修改了flag的值");
}
}
解决原子性问题:
public class Demo2 {
static AtomicInteger atomicInteger = new AtomicInteger();
public static void main(String[] args) {
for (int i = 0; i < 20000; i++) {
new Thread(() ->{
atomicInteger.addAndGet(1);
}).start();
}
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(atomicInteger.get());
}
}
指令重排:我们写的程序,计算机并不是按照你写的那样去执行的。
源代码 —> 编译器优化的重排 —> 指令并行也可能会重排 —> 内存系统也会重排 ——> 执行
处理器在执行指令重排的时候,会考虑:数据之间的依赖性
int x = 1; // 1
int y = 2; // 2
x = x + 5; // 3
y = x * x; // 4
我们希望的执行顺序是1234,但是计算机执行的顺序可能是1324或则2413,但不可能是4132。
有些指令重排不会造成结果的不同,但有些会,例如:
默认 a=0,b=0
| 线程A | 线程B |
| ----- | ----- |
| x = a | y = b |
| b =1 | a = 2 |
我们期望得到的结果是x=0,y=0;指令重排后可能得到x=2,y=1。
volatile可以避免指令重排,其工作原理是通过建立内存屏障禁止上下指令的顺序交换,如下图所示:
//单例模式 饿汉式
public class Hungry {
// 可能会浪费空间
private byte[] data1 = new byte[1024*1024];
private byte[] data2 = new byte[1024*1024];
private byte[] data3 = new byte[1024*1024];
private byte[] data4 = new byte[1024*1024];
private static Hungry hungry = new Hungry();
private Hungry() {
}
public Hungry getInstance() {
return hungry;
}
}
//单例模式 DCL懒汉式
public class Lazy {
/**
*一定要用volatile修饰,保证new Lazy();过程不指令重排
* 计算机指令执行顺序:
* 1. 分配内存空间
* 2、执行构造方法,初始化对象
* 3、把这个对象指向这个空间
*
* 期望顺序是:123
* 特殊情况下实际执行:132 ===> 此时 A 线程没有问题
* 当A线程执行到第3步,若额外加一个 B 线程 进来,B线程会认为lazy已经实例化了,
* 但此时lazy还没有完成构造。
*/
private volatile Lazy lazy;
private Lazy() {
}
public Lazy getInstance() {
if(lazy == null ){
synchronized (Lazy.class){
if(lazy == null){
lazy = new Lazy();
}
}
}
return lazy;
}
}
public class Holder {
private Holder () {
}
public Holder getInstance(){
return InnerClass.HOLDER;
}
public static class InnerClass{
private static Holder HOLDER = new Holder();
}
}
单例模式并不安全,一般的单例模式都可以通过反射创建多个实例,换句话说反射可以破坏单例!
//单例模式 DCL懒汉式
public class Lazy {
private volatile Lazy lazy;
private Lazy() {}
public Lazy getInstance() {
if(lazy == null ){
synchronized (Lazy.class){
if(lazy == null){
lazy = new Lazy();
}
}
}
return lazy;
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class lazyClazz = Lazy.class;
//获取构造方法
Constructor<Lazy> declaredConstructor = lazyClazz.getDeclaredConstructor(null);
//破坏构造方法的私有化
declaredConstructor.setAccessible(true);
//初始化第一个实例
Lazy lazy1 = declaredConstructor.newInstance();
//初始化第二个实例
Lazy lazy2 = declaredConstructor.newInstance();
System.out.println("layz1====>"+lazy1);
System.out.println("layz2====>"+lazy2);
}
}
执行结果:
public enum EnumSingle {
INSTANCE;
public EnumSingle getInstance() {
return INSTANCE;
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class enumSingleClazz = EnumSingle.class;
Constructor declaredConstructor = enumSingleClazz.getDeclaredConstructor(String.class, int.class);
declaredConstructor.setAccessible(true);
EnumSingle enumSingle = (EnumSingle) declaredConstructor.newInstance();
EnumSingle enumSingle2 = (EnumSingle) declaredConstructor.newInstance();
System.out.println("enumSingle1=====>"+enumSingle);
System.out.println("enumSingle2=====>"+enumSingle2);
}
}
执行结果:
错误原因:
什么是CAS?
CAS是CPU的开发原语。CAS全称CompareAndSet ,比较并更新。
public class CASDemo {
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(2020);
//符合期望 修改值
System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get());
//加1
atomicInteger.getAndIncrement();
//不符合期望,不更改
System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get());
}
}
AtomicInteger源码分析
CAS的问题:ABA问题,即一个线程将变量的值由2020改为2021,然后在改为2020,另外一个线程对该值的变化毫不知情。
带版本号 的原子操作!即乐观锁。
public class CASDemo {
public static void main(String[] args) throws InterruptedException {
AtomicStampedReference<Integer> atomicReference = new AtomicStampedReference(1,1);
//线程A
new Thread( () ->{
System.out.println(atomicReference.compareAndSet(1, 2,1,2));
System.out.println(atomicReference.getReference());
System.out.println(atomicReference.compareAndSet(2, 1,2,3));
System.out.println(atomicReference.getReference());
},"A").start();
TimeUnit.SECONDS.sleep(3);
//主线程
System.out.println(atomicReference.compareAndSet(1, 3,1,2));
System.out.println(atomicReference.getReference());
}
}
执行结果
公平锁: 非常公平, 不能够插队,必须先来后到!
非公平锁:非常不公平,可以插队 (默认都是非公平)
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
可重入锁(递归锁)
public class Demo01 {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(()->{
try {
phone.call();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"A").start();
new Thread(()->{
try {
phone.call();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B").start();
}
}
class Phone{
public synchronized void call() throws InterruptedException {
System.out.println(Thread.currentThread().getName()+"call=================");
TimeUnit.SECONDS.sleep(1);
msg();//这里也有锁(sms锁 里面的call锁)
}
public synchronized void msg(){
System.out.println(Thread.currentThread().getName()+"msg=================");
}
}
Lock 版
public class Demo02 {
public static void main(String[] args) {
Phone2 phone2 = new Phone2();
new Thread(()->{
try {
phone2.call();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"A").start();
new Thread(()->{
try {
phone2.call();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B").start();
}
}
class Phone2{
Lock lock = new ReentrantLock();
public void call() throws InterruptedException {
lock.lock();
try{
System.out.println(Thread.currentThread().getName()+"call=================");
TimeUnit.SECONDS.sleep(1);
msg();//这里也有锁(sms锁 里面的call锁)
}finally {
lock.unlock();
}
}
public void msg(){
lock.lock();
try{
System.out.println(Thread.currentThread().getName()+"msg=================");
}finally {
lock.unlock();
}
}
}
源码中的自旋锁
定义一个自旋锁
/**
* 自定义一个自旋锁
*/
public class MyLock {
//原子引用
AtomicReference<Thread> atomicReference = new AtomicReference<>();
//加锁
public void lock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"======>lock");
while (!atomicReference.compareAndSet(null,thread)){//加锁 自旋
}
}
//解锁
public void unlock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"======>unlock");
atomicReference.compareAndSet(thread,null);//解锁
}
}
public class Test {
public static void main(String[] args) {
MyLock myLock = new MyLock();
new Thread(()->{
myLock.lock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
myLock.unlock();
}
},"A").start();
new Thread(()->{
myLock.lock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
myLock.unlock();
}
},"B").start();
}
}
执行结果
死锁是什么
两个线程去抢夺对方的资源
public class DeadLock {
static Lock callLock = new ReentrantLock();
static Lock msgLock = new ReentrantLock();
public static void main(String[] args) {
Phone3 phone3 = new Phone3(callLock,msgLock);
Phone3 phone4 = new Phone3(msgLock,callLock);
new Thread(()->{
phone3.test();
},"A").start();
new Thread(()->{
phone4.test();
},"B").start();
}
}
class Phone3{
Lock callLock;
Lock msgLock;
public Phone3(Lock callLock, Lock msgLock) {
this.callLock = callLock;
this.msgLock = msgLock;
}
public void test(){
synchronized (callLock){
call();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (msgLock){
msg();
}
}
}
public void call(){
System.out.println(Thread.currentThread().getName()+"============call");
}
public void msg(){
System.out.println(Thread.currentThread().getName()+"============msg");
}
}
执行结果
如何排查:
2、 jstack查看堆栈信息 jstack 进程号
?
?
(完结,撒花)
原文:https://www.cnblogs.com/mc-rack/p/14622730.html