JUC-多线程进阶

JUC-多线程进阶
什么是JUC?
Java.util.concurrent
Java.util.concurrent.atomic 原子性
Java.util.concurrent.locks lock锁
线程与进程
一个进程可以包含多个线程,至少包含一个。
Java默认有几个线程?
2个,main、GC。
Java真的可以开启线程吗?
Java无法操作硬件,底层调用本地方法start0()。
并发与并行
并发:单核CPU,多线程操作同一个资源
并行:多核CPU,多个线程同时执行;线程池
并发编程的本质:充分利用CPU资源。
wait与sleep的区别
1)来自不同的类
wait==>Object
sleep==>Thread
2)关于锁的释放
wait会释放锁,sleep不会释放
3)使用的范围是不同的
wait必须在同步代码块中
sleep可以在任何地方
4)是否需要捕获异常
wait不需要捕获异常
sleep必须捕获异常
Lock锁
传统:synchronized
Lock是一个接口
用法:
1)Lock lock = new ReentrantLock();
2)lock.lock() //加锁
3)lock.unlock(); //释放锁
在这里插入图片描述
公平锁:十分公平,可以先来后到
非公平锁:可以插队(默认)
synchronized与Lock区别
1)synchronized是内置的java关键字,Lock是一个接口
2)synchronized无法获取锁的状态,Lock可以判断是否获得了锁
3)synchronized会自动释放锁,Lock必须手动释放锁,如果不释放锁,死锁。
4)synchronized可重入锁,不可以中断,非公平;Lock,可重入锁,可以中断锁,非公平(可设置)
5)synchronized适合锁少量的代码同步问题,Lock适合锁大量的同步代码!
生产者消费者问题
在这里插入图片描述

synchronized版

public class ProAndConDemo1 {
    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;
    public synchronized void increment() throws InterruptedException {
        if(number!=0){
            //等待
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
       //通知其他线程,+1完毕
        this.notifyAll();
    }
    public synchronized void decrement() throws InterruptedException {
        if(number==0){
            //等待
            this.wait();
        }
        number--;
      System.out.println(Thread.currentThread().getName()+"=>"+number);
        //通知其他线程,-1完毕
        this.notifyAll();
    }
}

问题存在:A,B,C,D四个线程。会出现虚假唤醒的问题。
将if改为while判断。

class Data{
    private int number = 0;
    public synchronized void increment() throws InterruptedException {
        while(number!=0){
            this.wait();
        }
        number++;
     System.out.println(Thread.currentThread().getName()+"=>"+number);
        this.notifyAll();
    }
    public synchronized void decrement() throws InterruptedException {
        while(number==0){
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        this.notifyAll();
    }
}

JUC版的生产者消费者问题
通过Lock找到Condition
在这里插入图片描述

public class ProAndConDemo2 {
    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();
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            while(number!=0){
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            condition.signalAll();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while(number==0){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            condition.signalAll();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }
}

Condition精准的通知和唤醒线程,让线程按指定顺序执行。

public class ProAndConDemo3 {
    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 number = 1;//1A 2B 3C
    public void printA(){
        lock.lock();
        try {
            while (number!=1){
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>AAAAA");
            number =2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void printB(){
        lock.lock();
        try {
            while (number!=2){
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>BBBBB");
            number =3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void printC(){
        lock.lock();
        try {
            while (number!=3){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>CCCCCCC");
            number =1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

8锁现象
如何判断锁的是谁
集合类不安全
并发修改异常:ConcurrentModificationException()。
List不安全

public class ListTest {
    public static void main(String[] args) {
        //并发下,线程不安全,synchronized
        /**
         * 解决方案
         * 1.List<String> list = new Vector<>();
         * 2.List<String> list = Collections.synchronizedList(new ArrayList<>()) ;
         * 3.List<String> list = new CopyOnWriteArrayList<>();
         *
         */
        //List<String> list = new ArrayList<>();
        //List<String> list = Collections.synchronizedList(new ArrayList<>()) ;
        //写入时复制, COW 计算机程序设计领域的一种优化策略
        //多个线程调用的时候,list,读取的时候,固定的,写入(覆盖)
        //在写入的时候避免覆盖,造成数据问题
        //Vector采用了Synchronized方法,CopyOnWriteArrayList效率比Vector高
        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不安全

/**
 * 1.Set<String> set = Collections.synchronizedSet(new HashSet<>()) ;
 * 2.Set<String> set = new CopyOnWriteArraySet<>();
 */
public class SetTest {
    public static void main(String[] args) {
        //Set<String> set = new HashSet<>();
        //Set<String> set = Collections.synchronizedSet(new HashSet<>()) ;
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i <= 10; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }
}

hashSet底层是什么?
底层就是hashMap。

  public HashSet() {
        map = new HashMap<>();
    }
  public boolean add(E e){
        return map.put(e,PRESENT==null);
  }

Map不安全

/**
 * 解决方案
 * 1.Collections.synchronizedMap(new HashMap<>());
 * 2. Map<String,String> map = new ConcurrentHashMap<>();
 */
public class MapTest {
    public static void main(String[] args) {
        //默认等级什么? new HashMap<>(16,0.75);
        //16表示桶大小,0.75表示加载因子
        //Map<String,String> map = new HashMap<>();
        Map<String,String> 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();
        }
    }
}

Callable
返回结果并可能引发异常的任务。实现者定义一个没有参数的单一方法,称为call。
Callable接口类似于Runnable,因为它们都是为其实例可能由另一个线程执行的类设计的。然而,A Runnable不反悔结果,也不能抛出被检查的异常。
1)可以有返回值
2)可以抛出异常
3)方法不同,run()/call()
细节:1)有缓存
2)结果可能需要等待,会阻塞

public class CallableTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyThread thread = new MyThread();
        FutureTask futureTask = new FutureTask(thread);
        new Thread(futureTask,"A").start();

        Integer o = (Integer) futureTask.get();
        System.out.println(o);
    }
}
class MyThread implements Callable<Integer>{

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

常用的辅助类
CountDownLatch
减法计数器。
countDownLatch.countDown();//数量减1
countDownLatch.await();//等待计数器归零,然后再向下执行
每次有线程调用countDown()数量-1,假设计数器变为零,然后再向下执行
CyclicBarrier
加法计数器。
Semaphore
信号量。
semaphore.aqcquire();//获得,假设结果已经满了,等待,等待被释放为止
semaphore.release();//释放,会将当前的信号量释放+1,然后唤醒线程

读写锁
ReadWriteLock
读可以被多线程同时读,写只能有一个线程写。

/**
 * 独占锁(写锁) 一次只能被一个线程占用
 * 共享锁(读锁)  多个线程可以同时占用
 * 读-读  可以共存
 * 读-写  不能共存
 * 写-写  不能共存
 */
public class ReadWriteDemo {
    public static void main(String[] args) {
        MyCacheLock myCacheLock = new MyCacheLock();
        //写入
        for (int i = 0; i < 5; i++) {
            final int tmp = i;
            new Thread(()->{
                myCacheLock.put(tmp+"",tmp+"");
            },String.valueOf(i)).start();
        }
        //读取
        for (int i = 0; i < 5; i++) {
            final int tmp = i;
            new Thread(()->{
                myCacheLock.get(tmp+"");
            },String.valueOf(i)).start();
        }
    }
}
class MyCacheLock{
    private volatile Map<String,Object> map = new HashMap<>();
    //读写锁:更加细腻度的控制
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    //存,写入的时候,只希望同时只有一个线程写
    public void put(String key,Object value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"写入"+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
    public void get(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}

阻塞队列
多线程并发处理、线程池,使用阻塞队列
在这里插入图片描述
四组API
在这里插入图片描述
1.抛出异常
2.不会抛出异常
3.阻塞等待
4.超时等待
SynchronousQueue同步队列
没有容量,进去一个元素,必须等待取出来之后,才能再往里面放一个元素!
put() take()

线程池
线程池:3大方法、7大参数、4种拒绝策略
程序的运行,本质:占用系统资源!优化资源的使用!=>池化技术
池化技术:事先准备好一些资源,有人要用,就来这里拿,用完之后再还回来
线程池的好处
1)降低资源的消耗
2)提高响应的速度
3)方便管理
线程复用、控制最大并发数、管理线程
3大方法

//Executors 工具类 3大方法
public class Demo1 {
    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 < 10; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
        //线程池用完,程序结束,关闭线程池
    }
}

7大参数

    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;
    }

在这里插入图片描述
使用工具类不安全,需要手动创建线程池

public class Demo2 {
    public static void main(String[] args) {
        //自定义线程池
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()//拒绝策略 抛出异常
        );
        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
        //线程池用完,程序结束,关闭线程池
    }
}

4种决绝策略

//满了,再进来,抛出异常
new ThreadPoolExecutor.AbortPolicy()//哪里来的回哪去
new ThreadPoolExecutor.CallerRunsPolicy()//队列满了,不会抛出异常
new ThreadPoolExecutor.DiscardPolicy()
//队列满了,尝试去和最早的竞争,也不会抛出异常!
new ThreadPoolExecutor.DiscardOldestPolicy()

拓展
最大线程到底该如何定义?
1)CPU密集型,几核是多少就定义为多少,可以保持CPU效率最高!

        //获取CPU的核数
        System.out.println(Runtime.getRuntime().availableProcessors());

2)IO密集型。大于程序中十分耗IO的线程的数量。
函数式接口
lambda表达式、链式编程、函数式接口、Stream流计算.
函数式接口:只有一个方法的接口。FunctionalInterface.
四大函数式接口:Consumer、Function、Predicate、Supplier
Function函数式接口:
在这里插入图片描述

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

断定型接口:有一个参数,返回值只能是布尔值
在这里插入图片描述

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

Consumer消费型接口:只有输入没有返回值
在这里插入图片描述

public class Demo3 {
    public static void main(String[] args) {
//        Consumer<String> consumer = new Consumer<String>() {
//            @Override
//            public void accept(String str) {
//                System.out.println(str);
//            }
//        };
        Consumer<String> consumer = (str)->{
            System.out.println(str);
        };
        consumer.accept("asd");
    }
}

Supplier供给型接口:没有输入只有返回值
在这里插入图片描述

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

Stream流式计算
大数据:存储+计算
存储:集合、MySQL本质就是存储东西的;计算都应该交给流来操作

/**
 * 题目要求:只用一行代码实现!
 * 现在有5个用户!筛选:
 * 1.ID必须是偶数
 * 2.年龄必须大于23岁
 * 3.用户名转为大写字母
 * 4.用户名字母倒着排序
 * 5.只输出一个用户!
 */
public class Demo1 {
    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(5,"e",25);
        //集合就是存储
        List<User> users = Arrays.asList(user1,user2,user3,user4,user5);
        //计算交给Stream流
        //lambda表达式、链式编程、函数式接口、Stream流计算
        users.stream()
                .filter(u->{return u.getId()%2==0;})
                .filter(u->{return u.getAge()>23;})
                .map(u->{return u.getName().toUpperCase();})
                .sorted((u1,u2)->{return u2.compareTo(u1);})
                .limit(1)
                .forEach(System.out::println);
    }
}

ForkJoin
ForkJoin在JDK1.7,并行执行任务!提高效率。大数据量。
大数据:Map Reduce(把大任务拆分为小任务)
在这里插入图片描述
ForkJoin特点:工作窃取
这个里面维护的是一个双端队列
异步回调
Future设计的初衷:对将来的某个事件的结果进行建模

/**
 * 异步回调:ajax
 * 异步调用:CompletableFuture
 * 异步执行,成功回调,失败回调
 */
public class Demo1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //发起一个请求
        //没有返回值的异步回调 runAsync
//        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName()+"runAsync=>Void");
//        });
//        System.out.println("1111");
//        completableFuture.get();//获取阻塞执行结果
        //有返回值的异步回调
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+"supplyAsync=>Integer");
            return 1024;
        });
        System.out.println(completableFuture.whenComplete((t, u) -> {
            System.out.println("t=>" + t);
            System.out.println("u=>" + u);
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 233; //可以获取到错误的返回结果
        }).get());
    }
}

JMM
面试题:请你谈谈Volatile的理解
Volatile是Java虚拟机提供轻量级的同步机制
1.保证可见性
2.不保证原子性
3.禁止指令重排
什么是JMM?
JMM:Java内存模型,不存在的东西,概念!约定
关于JMM的一些同步约定
1)线程解锁前,必须把共享变量立刻刷回主存
2)线程加锁前,必须读取主存中的最新值到工作内存中
3)加锁和解锁是同一把锁
线程 工作内存 主内存
8种操作
在这里插入图片描述
内存交互操作有8种
虚拟机实现必须保证每一个操作都是原子的,不可在分的(对于double和long类型的变量来说,load、store、read和write操作在某些平台上允许例外)
1)lock (锁定):作用于主内存的变量,把一个变量标识为线程独占状态
2)unlock (解锁):作用于主内存的变量,它把一个处于锁定状态的变量释放出来,释放后的变量才可以被其他线程锁定
3)read (读取):作用于主内存变量,它把一个变量的值从主内存传输到线程的工作内存中,以便随后的load动作使用
4)load (载入):作用于工作内存的变量,它把read操作从主存中变量放入工作内存中
5)use (使用):作用于工作内存中的变量,它把工作内存中的变量传输给执行引擎,每当虚拟机遇到一个需要使用到变量的值,就会使用到这个指令
6)assign (赋值):作用于工作内存中的变量,它把一个从执行引擎中接受到的值放入工作内存的变量副本中
7)store (存储):作用于主内存中的变量,它把一个从工作内存中一个变量的值传送到主内存中,以便后续的write使用
8)write  (写入):作用于主内存中的变量,它把store操作从工作内存中得到的变量的值放入主内存的变量中
JMM对这八种指令的使用,制定了如下规则:
1)不允许read和load、store和write操作之一单独出现。即使用了read必须load,使用了store必须write
2)不允许线程丢弃他最近的assign操作,即工作变量的数据改变了之后,必须告知主存
3)不允许一个线程将没有assign的数据从工作内存同步回主内存
4)一个新的变量必须在主内存中诞生,不允许工作内存直接使用一个未被初始化的变量。就是怼变量实施use、store操作之前,必须经过assign和load操作
5)一个变量同一时间只有一个线程能对其进行lock。多次lock后,必须执行相同次数的unlock才能解锁
6)如果对一个变量进行lock操作,会清空所有工作内存中此变量的值,在执行引擎使用这个变量前,必须重新load或assign操作初始化变量的值
7)如果一个变量没有被lock,就不能对其进行unlock操作。也不能unlock一个被其他线程锁住的变量
8)对一个变量进行unlock操作之前,必须把此变量同步回主内存
Volatile
1)保证可见性

public class Demo1 {
    //不加volatile程序就会死循环
    //加volatile可以保证可见性
    private volatile  static int num = 0;
    public static void main(String[] args) {
        new Thread(()->{//线程1对主内存的变化不知道的
            while (num==0){

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

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

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

如果不加lock和synchronized,如何保证原子性。
使用原子类解决原子性问题。

    //volatile不保证原子性
    //原子类的Integer
    private volatile static AtomicInteger num = new AtomicInteger();
    public static void add(){
        //num++;
        num.getAndIncrement(); //AtomicInteger + 1,方法 CAS
    }

3)禁止指令重排
什么是指令重排:计算机并不是按照你写的那样去执行的
源代码–>编译器优化的重排–>指令并行也可能会重排–>内存系统也会重排–>执行
处理器在进行指令重排的时候,会考虑:数据之间的依赖性。
Volatile可以避免指令重排
内存屏障。CPU指令。作用:
1.保证特定的操作执行顺序!
2.可以保证某些变量的内存可见性(利用volatile实现了可见性)
在这里插入图片描述
总结
Volatile是可以保持可见性。不能保证原子性,由于内存屏障,可以保证避免指令重排的发生。
单例模式
饿汉式、DCL懒汉式。
饿汉式
深入理解CAS
什么是CAS,comparedAndSet.
CAS:比较当前工作内存中的值和主内存中的值,如果这个值是期望的,那么执行操作!如果不是就一直循环(底层是自旋锁)
缺点:
1)循环会耗时
2)一次性只能保证一个共享变量的原子性
3)ABA问题
A的期望值为1,B的期望值也为1,B的执行速度快将1改为3,再改回了1;A再拿到1的值,这时该值已经被改变过了
在这里插入图片描述
解决ABA问题,引入原子引用。对应的思想:乐观锁。
各种锁的理解
公平锁、非公平锁
公平锁:非常公平、不能够插队,必须先来后到
非公平锁:非常不公平、可以插队(默认都是非公平)
可重入锁(递归锁)
拿到了外面的锁之后,就可以拿到里面的锁,自动获得。lock锁必须配对使用(lock,unlock)
在这里插入图片描述

自旋锁
死锁
在这里插入图片描述
如何排除死锁?
1.jps定位进程号 jps -l
2.使用’jstack’进程号找到死锁

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值