JUC学习

JUC编程笔记

1:什么是JUC

java.util.concurrent包下的

2:线程和进程

进程:一个程序,QQ.exe,Music.exe 程序的集合。一个进程最少包含一个线程

线程:CPU调度的最小单位

java默认两个线程:Main线程 GC线程

并发(可以处理多个任务,不一定同时),并行(同时处理多个任务)

并发编程:并发,并行

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

  • CPU一核,模拟出来多条线程,快速切换

并行(多个人一起行走)

  • CPU多核,多个线程可以同时执行;线程池

线程有几个状态

		#创建状态
        NEW,
		#运行
        RUNNABLE,
		#阻塞
        BLOCKED,
		#等待(死死的等)
        WAITING,
		#超时等待(有时间限制的等)
        TIMED_WAITING,
		#终止
        TERMINATED;

wait和sleep的区别

1:来自不同的类

wait=>Object

sleep=>Thread

2:关于锁的释放

wait会释放锁,sleep睡觉,抱着锁睡觉,不会释放

3:使用的范围是不同

wait:必须在同步代码块中

sleep:可以在任何地方睡

3:Lock锁

传统的Synchronized

Lock接口

ReentrantLock 可重入锁
ReadLock 读锁
WriteLock 写锁

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

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

Synchronized和Lock区别

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

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

4:生产者和消费者问题

#传统的synchronized 和 wait notifyAll
public class Test {
    public static void main(String[] args) {
        Data data=new Data();
        //开启两个线程去争夺
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                data.increment();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                data.decrement();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                data.increment();
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                data.decrement();
            }
        },"D").start();
    }
}
//线程交互操作
class Data{
    private int num=0;
    //+1
    public synchronized void increment(){
        //为了防止虚假唤醒,所有的wait都必须在循环中
        //如果num大于0
        while(num>0){
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        num++;
        System.out.println(Thread.currentThread().getName()+"->"+num);
        //唤醒其它线程
        notifyAll();

    }
    //-1
    public synchronized void decrement(){
        //如果num小于0
        while(num<=0){
            //等待
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        num--;
        System.out.println(Thread.currentThread().getName()+"->"+num);
        //唤醒其它线程
        notifyAll();
    }
}
#JUC版的生产者消费者问题 Lock conditional.awit() conditional.signal()
public class JucTest {
    public static void main(String[] args) {
        Data2 data=new Data2();
        //开启两个线程去争夺
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                data.increment();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                data.decrement();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                data.increment();
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                data.decrement();
            }
        },"D").start();
    }
}
//线程交互操作
class Data2{
    private Lock lock=new ReentrantLock();
    private Condition condition=lock.newCondition();
    private int num=0;
    //+1
    public void increment(){
        lock.lock();
        //为了防止虚假唤醒,所有的wait都必须在循环中
        //如果num大于0
        try {
            while(num>0) {
                //等待
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"->"+num);
            //唤醒其它线程
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            //解锁
            lock.unlock();
        }

    }
    //-1
    public synchronized void decrement(){

        lock.lock();
        try {
            //如果num小于0
            while(num<=0) {
                //等待
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"->"+num);
            //唤醒其它线程
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            //解锁
            lock.unlock();
        }



    }
}

Condition的优势,精准的通知和唤醒线程

public class ConditionTest {

    public static void main(String[] args) {
        Data3 data=new Data3();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                data.A();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                data.B();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                data.C();
            }
        },"C").start();

    }
}
class Data3{
    private Lock lock=new ReentrantLock();
    private Condition condition1=lock.newCondition();
    private Condition condition2=lock.newCondition();
    private Condition condition3=lock.newCondition();
    int number=1;
    public void A(){
        //number为1执行A,number为2执行B,number为3执行C
        lock.lock();
        try {
            while(number!=1){
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"执行了A方法");
            number=2;
            //唤醒执行线程B
            condition2.signal();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }

    }
    public void B(){
        //number为1执行A,number为2执行B,number为3执行C
        lock.lock();
        try {
            while(number!=2){
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName()+"执行了B方法");
            number=3;
            //唤醒执行线程B
            condition3.signal();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }
    public void C(){
        //number为1执行A,number为2执行B,number为3执行C
        lock.lock();
        try {
            while(number!=3){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"执行了C方法");
            number=1;
            //唤醒执行线程B
            condition1.signal();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }

}

5:8锁现象

如何判断锁的是谁!永远

/*
* 八锁问题:
* 1:标准情况下,两个线程打印 ,先发短信还是先打电话,答案是先发短信
* 2:在发短信的时候增加睡眠,两个线程打印 ,先发短信还是先打电话,答案还是先发短信,因为sleep
* 不会释放锁
*
 */
public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        Phone1 phone=new Phone1();
//        Phone1 phone2=new Phone1();
        //开启两个线程
        new Thread(()->{
            phone.send();
        },"A").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            phone.call();
//            phone2.call();
        },"B").start();
    }
}
class Phone1{
    //synchronized锁的对象是方法的调用者
    //两个方法拿到的是同一个锁,谁先拿到谁先执行
    public synchronized void send() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("发送消息");
    }
    public synchronized void call(){
        System.out.println("打电话");
    }
}

/**
 * 3:增加普通方法hello的情况下先打印发消息还是hello
 * 答案是先hello,因为hello方法没有加锁,不需要等待
 * 4:使用两个对象的情况下先打印发消息还是打电话
 *答案是先打电话,因为它们锁的不是同一个对象,发送消息的锁不影响
 * 打电话的锁
 */
public class Test2 {
    public static void main(String[] args) throws InterruptedException {
        Phone2 phone=new Phone2();
        Phone2 phone2=new Phone2();
        //开启两个线程
        new Thread(()->{
            phone.send();
        },"A").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
//            phone.hello();
            phone2.call();
        },"B").start();
    }
}
class Phone2{
    //synchronized锁的对象是方法的调用者
    //两个方法拿到的是同一个锁,谁先拿到谁先执行
    public synchronized void send() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("发送消息");
    }
    public synchronized void call(){
        System.out.println("打电话");
    }
    public void hello(){
        System.out.println("hello");
    }
}

**
 * 5:增加两个静态的同步方法,同一个对象的情况下是先发消息还是先打电话
 * 6:两个对象的情况下,是先发消息还是先打电话
 *
 * 答案:都是先发消息,因为静态锁锁的是整个Class文件,所以不管是New几个对象,都是在同一静态锁下
 *
 */
public class Test3 {
    public static void main(String[] args) throws InterruptedException {
        Phone3 phone=new Phone3();
        Phone3 phone2=new Phone3();
        //开启两个线程
        new Thread(()->{
            phone.send();
        },"A").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
//            phone.hello();
           phone2.call();
//            phone.call();
        },"B").start();
    }
}
class Phone3{
    //synchronized锁的对象是方法的调用者
    //两个方法拿到的是同一个锁,谁先拿到谁先执行
    public static synchronized void send() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("发送消息");
    }
    public static synchronized void call(){
        System.out.println("打电话");
    }
    public void hello(){
        System.out.println("hello");
    }
}
/**
 * 7:一个静态同步方法,一个普通同步方法,是先发消息还是先打电话
 * 答案:先打电话,因为它们是不同的锁,一个是Class类锁,一个是对象锁
 * 8:一个静态同步方法,一个普通同步方法,两个对象,是先发消息还是先打电话
 *  * 答案:先打电话,因为它们是不同的锁,一个是Class类锁,一个是对象锁
 */
public class Test4 {
    public static void main(String[] args) throws InterruptedException {
        Phone4 phone=new Phone4();
        Phone4 phone2=new Phone4();
        //开启两个线程
        new Thread(()->{
            phone.send();
        },"A").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
//            phone.hello();
            phone2.call();
//            phone.call();
        },"B").start();
    }
}
class Phone4{
    //synchronized锁的对象是方法的调用者
    //两个方法拿到的是同一个锁,谁先拿到谁先执行
    public static synchronized void send() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("发送消息");
    }
    public synchronized void call(){
        System.out.println("打电话");
    }
    public void hello(){
        System.out.println("hello");
    }
}

总结,主要还是判断锁的是Class类模板还是锁对象

6:集合类不安全

List不安全

public class ListTest {
    public static void main(String[] args) {
        /**
         * List默认非线程安全,如果想要线程安全,可以使用Vector
         * 第一种方案:List<String> list = new Vector<>();
         * 第二种方案:List<String> list= Collections.synchronizedList(new ArrayList<>());
         * 第三种方案:List<String> list= new CopyOnWriteArrayList<>();
         */
//        List<String> list = new ArrayList<>();
//        List<String> list = new Vector<>();
//        List<String> list= Collections.synchronizedList(new ArrayList<>());
        /**
         *CopyOnWrite写入时复制,在写入数据的时候并不是直接写入要修改的位置,而是把数据线复制
         * 到另一个位置再进行修改,然后把修改后的数据set回去
         * final ReentrantLock lock = this.lock;
         *         lock.lock();
         *         try {
         *             Object[] elements = getArray();
         *             int len = elements.length;
         *             Object[] newElements = Arrays.copyOf(elements, len + 1);
         *             newElements[len] = e;
         *             setArray(newElements);
         *             return true;
         *         } finally {
         *             lock.unlock();
         *         }
         *
         */
        List<String> list= new CopyOnWriteArrayList<>();
        for (int i = 1; i <= 100; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(list);
            },i+"").start();
        }


    }
}

Set不安全

/**
 * 同理可知HashSet不安全
 *
 */
public class SetTest {
    public static void main(String[] args) {
        /**
         * Set默认非线程安全,如果想要线程安全
         * 第一种方案:Set<String > set= Collections.synchronizedSet(new HashSet<>());
         * 第二种方案:Set<String> set= new CopyOnWriteArraySet<>();
         */
//        Set<String > set=new HashSet<>();
//        Set<String > set= Collections.synchronizedSet(new HashSet<>());
        Set<String> set= new CopyOnWriteArraySet<>();
        for (int i = 1; i <= 100; 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<>();
    }
    //map的Key不会重复,所有HashSet不会有重复的值
   public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

Map不安全

/**
 * @author liusigou
 * @create 2021--01--04--20:28
 */
public class MapTest {
    public static void main(String[] args) {
        //初始加载因子0.75 为什么是0.75呢?从泊松分布的图得出来的结果
        //基础容量是16
        /**
         * Map默认非线程安全,如果想要线程安全
         * 第一种方案:Map<String > map= Collections.synchronizedMap(new HashMap<>());
         * 第二种方案:Map<String> map= new ConcurrentHashMap<>();
         */
//        Map<String,String> map=new HashMap<>();
        Map<String,String> map=new ConcurrentHashMap<>();
        for (int i = 1; i <= 100; i++) {
            new Thread(()->{
                map.put(UUID.randomUUID().toString().substring(0,5),"");
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }
}

7:Callable

  1. 可以有返回值
  2. 可以抛出异常
  3. 调用方法不同 call()
public class CallableTest {
    public static void main(String[] args) {
        /**
         * new Thread(这里面只能用new Runnable)
         * 然后由于我们相拥Callable,就必须要找到能够连接Runnable和Callable的接口
         * public class FutureTask<V> implements RunnableFuture<V> {
         *     public FutureTask(Callable<V> callable) {
         *         if (callable == null)
         *             throw new NullPointerException();
         *         this.callable = callable;
         *         this.state = NEW;       // ensure visibility of callable
         *     }
         * }
         * public interface RunnableFuture<V> extends Runnable, Future<V> {}
         *从上面的源码可以看到FutureTask能够跟Callable挂上关系
         * 又由于FutureTask实现了RunnableFuture,RunnableFuture实现了Runnable接口
         * 所以FutureTask既能跟Callable搭上关系,也能跟Runnable搭上关系
         */
        MyThread myThread=new MyThread();
        FutureTask futureTask=new FutureTask(myThread);
        new Thread(futureTask,"A").start();
        new Thread(futureTask,"B").start();//结果会被缓存
        Integer o= null;
        try {
            //get方法可能会产生阻塞,把他放在最后,或者使用异步通信
            o = (Integer)futureTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(o);
    }
}
class MyThread implements Callable<Integer>{

    public Integer call() {
        System.out.println("call()");
        return 1024;
    }
}

细节注意:

  1. 有缓存
  2. 结果可能需要等待,会阻塞

8:常用的辅助类

8.1 CountDownLatch

public class CountDownLatchDemo {
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 0; i < 6; i++) {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"Go Out");
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
        try {
            countDownLatch.await();//等待计数器归零才往下走
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("关门");
    }
}
#减法计数器

8.2 CyclicBarrier

public class CyclicBarrierDemo {
    public static void main(String[] args) {
        /**
         * 集齐七颗龙珠召唤神龙
         */
        CyclicBarrier cyclicBarrier=new CyclicBarrier(7,()->{
            System.out.println("召唤神龙成功");
        });
        for (int i = 0; i < 7; i++) {
            final int temp=i;
            new Thread(()->{
                System.out.println(temp);
                try {
                    cyclicBarrier.await();//这个线程会阻塞,直到有7个线程阻塞了之后再一起
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
#加法计数器

8.3 Semaphore

public class SemaphoreDemo {
    public static void main(String[] args) {
        //3个停车位
        Semaphore semaphore=new Semaphore(3);
        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                //得到车位
                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();释放,会将当前的信号量释放+1,然后唤醒等待的资源
作用:多个资源互斥的使用!并发限流,控制最大的线程数

9:读写锁

/**
 * 独占锁(写锁)
 * 共享锁(读锁)
 * ReadWriteLock
 * 读-读 可以共存
 * 读-写 不能共存
 * 写-写 不能共存
 * 之所以读也要加锁,是为了防止在写的时候读,从而引发脏读
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCatch myCatch=new MyCatch();
        //这五个线程只做写入
        for (int i = 0; i < 5; i++) {
            final int temp=i;
            new Thread(()->{
                myCatch.set(temp+"",temp+"");
            },String.valueOf(i)).start();
        }
        //这五个线程只做读取
        for (int i = 0; i < 5; i++) {
            final int temp=i;
            new Thread(()->{
                Object o = myCatch.get(temp + "");
                System.out.println(o);
            },String.valueOf(i)).start();
        }
    }
}
//自定义缓存 加锁
class MyCatch2{
    private volatile Map<String,Object> map=new HashMap<>();
    private ReentrantReadWriteLock lock=new ReentrantReadWriteLock();
    //读
    public Object get(String key){
        //读的时候所有人都能读
        lock.readLock().lock();
        Object o=null;
        try {
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            o = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取OK");
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.readLock().unlock();
        }
        return o;
    }
    //写
    public void set(String key,Object value){
        //写入的时候只希望只有一个线程去写
        lock.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 {
            lock.writeLock().unlock();
        }

    }
}
//自定义缓存
class MyCatch{
    private volatile Map<String,Object> map=new HashMap<>();
    //读
    public Object get(String key){
        System.out.println(Thread.currentThread().getName()+"读取"+key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取OK");
        return o;
    }
    //写
    public void set(String key,Object value){
        System.out.println(Thread.currentThread().getName()+"写入"+key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入OK");
    }
}

10:阻塞队列

阻塞:当试图进行某个动作时,由于某种原因进入等待状态

队列:一个先进先出的数据结构

阻塞队列形成堵塞的原因

  1. 写入:如果队列满了,就必须阻塞等待
  2. 取出:如果队列是空的,就必须阻塞等待生产

在这里插入图片描述

什么情况下会使用阻塞队列:多线程并发处理,线程池

四组API

方式抛出异常有返回值,不抛出异常阻塞,等待超时等待
添加addofferputoffer
移除removepolltakepoll
判断队列首elementpeek
  1. 抛出异常

    public class Test {
        public static void main(String[] args) {
            Test.test();
        }
        /**
         * 抛出异常
         */
        public static void test(){
            ArrayBlockingQueue queue=new ArrayBlockingQueue(3);
            System.out.println(queue.add("A"));
            System.out.println(queue.add("b"));
            System.out.println(queue.add("C"));
            System.out.println(queue.add("D"));
            //查看队首元素
            System.out.println(queue.element());
            System.out.println("=====================");
    		System.out.println(queue.remove());
            System.out.println(queue.remove());
            System.out.println(queue.remove());
        }
    }
    #结果
    true
    true
    true
    Exception in thread "main" java.lang.IllegalStateException: Queue full
    
  2. 不会抛出异常

    /**
         * 不会抛出异常
         */
        public static void test2(){
            ArrayBlockingQueue queue=new ArrayBlockingQueue(3);
            System.out.println(queue.offer("A"));
            System.out.println(queue.offer("b"));
            System.out.println(queue.offer("C"));
            System.out.println(queue.offer("D"));
            System.out.println("=====================");
            System.out.println(queue.poll());
            System.out.println(queue.poll());
            System.out.println(queue.poll());
            System.out.println(queue.poll());
        }
     #结果
     true
    true
    true
    false
    =====================
    A
    b
    C
    null
    
  3. 阻塞等待

    /**
         * 阻塞,等待
         */
        public static void test3(){
            ArrayBlockingQueue queue=new ArrayBlockingQueue(3);
            try {
                queue.put("A");
                queue.put("B");
                queue.put("C");
    //            queue.put("D");
                System.out.println(queue.take());
                System.out.println(queue.take());
                System.out.println(queue.take());
                System.out.println(queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
        }
        #结果,如果在添加的时候或者取出的时候,队列处于饱和或者空的情况下,就会阻塞等待
    
  4. 超时等待

/**
     * 超时等待
     */
    public static void test4(){
        ArrayBlockingQueue queue=new ArrayBlockingQueue(3);
        try {
            System.out.println(queue.offer("A",2, TimeUnit.SECONDS));
            System.out.println(queue.offer("b",2, TimeUnit.SECONDS));
            System.out.println(queue.offer("C",2, TimeUnit.SECONDS));
            System.out.println(queue.offer("D",2, TimeUnit.SECONDS));
            System.out.println("=====================");
            System.out.println(queue.peek());
            System.out.println(queue.poll());
            System.out.println(queue.poll());
            System.out.println(queue.poll());
            System.out.println(queue.poll(2, TimeUnit.SECONDS));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
     #结果,如果在添加的时候或者取出的时候,队列处于饱和或者空的情况下,就会阻塞等待,但是2秒后就会结束等待

同步队列

/**
 * 同步队列
 */
public class SynchronousQueueDemo {
    public static void main(String[] args) {
        BlockingQueue queue=new SynchronousQueue<>();
        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName()+"put 1");
                queue.put(1);
                System.out.println(Thread.currentThread().getName()+"put 2");
                queue.put(2);
                System.out.println(Thread.currentThread().getName()+"put 3");
                queue.put(3);

            }
            catch (Exception e){
                e.printStackTrace();
            }
        },"A").start();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+queue.take());
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+queue.take());
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+queue.take());

            }
            catch (Exception e){
                e.printStackTrace();
            }
        },"B").start();

    }
}
###结果
Aput 1
B1
Aput 2
B2
Aput 3
B3

11:线程池

池化技术:三大方法,7大参数,4种拒绝策略

程序的运行,本质,占用系统资源完成某个功能

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

池化技术:事先准备好一些资源,有人要用,就来池子拿,用完就放回去

线程池的好处:

  1. 降低资源的消耗
  2. 提高响应的速度
  3. 方便管理

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

/**
 * @author liusigou
 * @create 2021--01--06--20:53
 */
public class Demo01 {
    public static void main(String[] args) {
        //单个线程的线程池
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        try {
            //        //固定的线程
//        Executors.newFixedThreadPool(5);
//        //可伸缩的,遇强则强
//        Executors.newCachedThreadPool();
            for (int i = 0; i < 10; 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的本质 
 ###
 corePoolSize:核心线程池大小
 maximumPoolSize:最大线程池大小
 keepAliveTime:超时没有人调用就会释放
 unit:超时单位
 workQueue:阻塞队列
 threadFactory:线程工厂
 handler:拒绝策略
 ###
 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;
    }

在这里插入图片描述

手动创建一个线程池

//自定义线程池
        ExecutorService threadPool= new ThreadPoolExecutor(2, 5,
                3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());

四种拒绝策略

//new ThreadPoolExecutor.AbortPolicy()这个拒绝策略是当线程池满了,阻塞队列也满了,就不处理,抛出异常
//new ThreadPoolExecutor.CallerRunsPolicy()哪来的去哪里 mainok
//new ThreadPoolExecutor.DiscardPolicy()队列满了就丢掉任务,不抛出异常
//new ThreadPoolExecutor.DiscardOldestPolicy()尝试跟最早的竞争,不抛出异常

最大线程应该如何定义

  1. CPU密集型,几核就是使用几,可以保持CPU效率最高
  2. IO密集型 判断程序十分耗io的线程,io十分占用资源
//这里的最大线程池数应该使用代码获取
        //获取CPU核数Runtime.getRuntime().availableProcessors()
        System.out.println(Runtime.getRuntime().availableProcessors());
        ExecutorService threadPool= new ThreadPoolExecutor(2, 5,
                3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());

12:ForkJoin

什么是ForkJoin

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

在这里插入图片描述

ForkJoin特点:工作窃取

假设同时有A,B两个线程在执行任务,B线程已经完成,A线程还有任务未执行完毕,此时B线程就会从A线程窃取任务来执行,这就是工作窃取

ForkJoin的操作

/**
 * 如何使用ForkJoin
 * 1:forkJoinPool,通过它来执行
 * 2:计算任务forkJoinPool.execute(ForkJoinTask task)
 * 3:计算类要继承ForkJoinTask
 */
public class ForkJoinDemo extends RecursiveTask<Long> {
    private Long start;
    private Long end;
    private Long temp=10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }


    @Override
    protected Long compute() {
        Long result=0L;
        //计算方法,如果start-end<temp,则不进行分支合并计算
        if(start-end<temp){
            for (Long i = start; i < end; i++) {
                result+=i;
            }
            return result;
        }else{
            long middle = (start + end) / 2;
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            task1.fork();//任务拆分,把任务压入线程队列
            ForkJoinDemo task2= new ForkJoinDemo(middle, end);
            task2.fork();//任务拆分,把任务压入线程队列
            return task1.join()+task2.join();

        }
    }
}
public class Test {
    public static void main(String[] args) {
//        test1();//7204
//        test2();//6126
        test3();//656
    }
    public static void test1(){
        Long result=0L;
        long startDate = System.currentTimeMillis();
        for (Long i = 0L; i < 10_0000_0000; i++) {
            result+=i;
        }
        long endDate = System.currentTimeMillis();
        System.out.println(endDate-startDate);
        System.out.println(result);
    }
    public static void test2(){
        Long result=0L;
        ForkJoinPool forkJoinPool=new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo(0L, 10_0000_0000L);
        long startDate = System.currentTimeMillis();
        forkJoinPool.execute(task);
        try {
            result=task.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        long endDate = System.currentTimeMillis();
        System.out.println(endDate-startDate);
        System.out.println(result);
    }
    public static void test3(){
        Long result=0L;
        long startDate = System.currentTimeMillis();
        result= LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
        long endDate = System.currentTimeMillis();
        System.out.println(endDate-startDate);
        System.out.println(result);
    }
}

13:异步回调

/**
 * 异步调用
 */
public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Void> completedFuture=CompletableFuture.runAsync(()->{
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            System.out.println(Thread.currentThread().getName()+"runAsync=>Void");
        });
        System.out.println("1111");
        completedFuture.get();
        CompletableFuture<Integer> completedFuture2=CompletableFuture.supplyAsync(()->{
            System.out.println(Thread.currentThread().getName()+"supplyAsync=>Integer");
            int i=10/0;
            return 1024;
        });
        System.out.println("------------------");
        //当成功的时候
        System.out.println(completedFuture2.whenComplete((t, u) -> {
            System.out.println("t=>" + t);//正确的返回结果
            System.out.println("u=>" + u);//异常的返回结果
        }).exceptionally((e) -> {
            //当失败的时候
            System.out.println(e.getMessage());
            return -1;
        }).get());

    }
}

14:JMM

请你谈谈你对Volatile的理解

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

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

什么是JMM

JMM:java内存模型,不存在的东西,是一个概念!阅读

关于JMM的一些同步的约定:

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

线程工作内存,主内存

8种操作:
在这里插入图片描述
在这里插入图片描述

15:Volatile

保证可见性

public class JMMDemo {
    private static volatile int num=0;
    public static void main(String[] args) {
        new Thread(()->{
            while (num==0){

            }
            System.out.println("线程A结束");
        }).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        num=1;
        System.out.println(num);
    }
}

不保证原子性

原子性:不可分割

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

public class VolatileDemo {
    private volatile static int num=0;
    public static void add(){
        num++;
    }
    public static void main(String[] args) {
        //20个线程
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 1000; i1++) {
                    add();
                }
            }).start();
        }
        //默认两个线程main gc,如果线程数大于0,主线程礼让
        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println(num);
    }
}

如果不适用Synchronized和Lock的话,可以使用原子类来保证原子性

public class VolatileDemo {
    private volatile static AtomicInteger num=new AtomicInteger();

    public static void add(){
        num.getAndIncrement();//CAS
    }
    public static void main(String[] args) {
        //20个线程
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 1000; i1++) {
                    add();
                }
            }).start();
        }
        //默认两个线程main gc,如果线程数大于0,主线程礼让
        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println(num);
    }
}

指令重排

什么是指令重排:我们所写的程序,计算机并不是按我们所写的顺序执行的

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

处理器进行指令重排的时候,会考虑数据的依赖关系

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

我们所期待的结果步骤1234
但是可能执行的是2134 1324
但是不可能是4123这样的改变有依赖关系的位置

volatile可以避免指令重排

内存屏障,CPU指令。作用:

  1. 保证特定的操作的执行顺序
  2. 保证某些遍历的内存可见性

在这里插入图片描述

16:深入理解CAS

什么是CAS

public class CASDemo {
    public static void main(String[] args) {
        //CAS
        AtomicInteger atomicInteger=new AtomicInteger(2020);
        //public final boolean compareAndSet(int expect, int update)
        //如果期望值符合,那就更新
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(2020, 2022));
        System.out.println(atomicInteger.get());
        atomicInteger.getAndIncrement();
    }
}

什么是Unsafe类
在这里插入图片描述

var1 var2 var4分别代表对象本身,内存偏移值,要修改的值,整体意思就是先获取对象本身及内存偏移值,从而获取到主内存地址的值,然后与工作内存的值进行比较,如果相等,就进行修改如果不相等就一直循环

缺点:

  1. 循环会耗时
  2. 一次性只能保证一个共享变量的原子性
  3. 会导致ABA问题

CAS:ABA问题(狸猫换太子)
在这里插入图片描述

17:原子引用

带版本号的修改
在这里插入图片描述

public class CASDemo02 {
    public static void main(String[] args) {
        //注意,如果泛型是个包装类,注意对象的引用问题
        AtomicStampedReference<Integer> atomic = new AtomicStampedReference<Integer>(20,1);
        new Thread(()->{
            //先获得版本号
            int stamp=atomic.getStamp();
            System.out.println("a1=>"+stamp);
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            System.out.println(atomic.compareAndSet(20, 22, atomic.getStamp(), atomic.getStamp() + 1));
            System.out.println("a2=>"+atomic.getStamp());
            System.out.println(atomic.compareAndSet(22, 20, atomic.getStamp(), atomic.getStamp() + 1));
            System.out.println("a3=>"+atomic.getStamp());
        },"A").start();
        new Thread(()->{
           //先获得版本号
            int stamp=atomic.getStamp();
            System.out.println("b1=>"+stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(atomic.compareAndSet(20, 66, stamp, stamp + 1));
            System.out.println("b1=>"+stamp);
        },"B").start();
    }
}

18:各种锁的理解

1:公平锁,非公平锁

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

非公平锁:非常不公平,可以插队,线程可以插队(默认非公平锁,主要是因为有可能有一个线程先执行,但是需要3h,另一个线程需要3s,这个时候如果采用公平锁的话就性能低下了)

public ReentrantLock() {
        sync = new NonfairSync();
    }
public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

2:可重入锁

synchronized版

public class Demo01 {
    public static void main(String[] args) {
        Phone phone=new Phone();
        new Thread(()->{
            phone.sms();
        },"A").start();
        new Thread(()->{
            phone.sms();
        },"B").start();
    }
}
class Phone{
    public synchronized void sms(){
        System.out.println(Thread.currentThread().getName()+"sms");
        call();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public synchronized void call(){
        System.out.println(Thread.currentThread().getName()+"call");
    }
}

Lock版

public class Demo02 {
    public static void main(String[] args) {
        Phone2 phone=new Phone2();
        new Thread(()->{
            phone.sms();
        },"A").start();
        new Thread(()->{
            phone.sms();
        },"B").start();
    }
}
class Phone2{
    Lock lock=new ReentrantLock();
    public void sms(){
        lock.lock();
        //Lock锁必须配对,不然就会死锁
        try {
            System.out.println(Thread.currentThread().getName()+"sms");
            call();
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }

    }
    public void call(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"call");
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }

    }
}

注意:synchronized是一把锁,Lock是两个锁

3:自旋锁

//自旋锁
public class SpinLockDemo {
    //引用类型的原子类
    AtomicReference<Thread> atomicReference=new AtomicReference<>();
    //加锁
    public void myLock(){
        Thread thread=Thread.currentThread();
        System.out.println(thread.getName()+"进入myLock()");
        //自旋锁
        while(!atomicReference.compareAndSet(null,thread)){

        }
    }
    //解锁
    public void myUnLock(){
        Thread thread=Thread.currentThread();
        System.out.println(thread.getName()+"进入myUnLock()");
        atomicReference.compareAndSet(thread,null);
    }
}
public class TestSpinLock {
    public static void main(String[] args) {
//        Lock lock=new ReentrantLock();
//        lock.lock();
//        lock.unlock();
        SpinLockDemo spinLockDemo=new SpinLockDemo();
        new Thread(()->{
            spinLockDemo.myLock();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                spinLockDemo.myUnLock();
            }
        },"A").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            spinLockDemo.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                spinLockDemo.myUnLock();
            }
        },"B").start();


    }
}

4:死锁

死锁是什么

public class DeadLock {
    public static void main(String[] args) {
        String lockA="lockA";
        String lockB="lockB";
        new Thread(new MyThread(lockA,lockB),"T1").start();
        new Thread(new MyThread(lockB,lockA),"T2").start();
    }
}
class MyThread implements Runnable{
    private String lockA;
    private String lockB;

    public MyThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName()+" lock:"+lockA+"=>get"+lockB);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB){
                System.out.println(Thread.currentThread().getName()+" lock:"+lockB+"=>get"+lockA);
            }
        }
    }
}
#A尝试获取B锁,B尝试获取A锁,造成了死锁

解决问题

  1. 使用jps -l定位进程号

在这里插入图片描述

  1. 使用jstack 进程号 查看进行信息

在这里插入图片描述

面试,工作中!排查问题:

  1. 日志
  2. 堆栈
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值