Day17 2021.4.1 JUC并发编程-上

Day17 2021.4.1

JUC并发编程

概述

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dKE6Zc5f-1617262965142)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401100735717.png)]

java.util 工具包、包、分类

业务:普通的线程代码 Thread

Runnable 没有返回值、效率相比入 Callable 相对较低

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bbwRSxtZ-1617262965144)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401100809411.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qizOFYPc-1617262965145)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401100818055.png)]

并发编程:并发、并行

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

CPU 一核 ,模拟出来多条线程,天下武功,唯快不破,快速交替

并行(多个人一起行走)

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

public class Test1 { 
	public static void main(String[] args) { 
	// 获取cpu的核数 
	// CPU 密集型,IO密集型 
	System.out.println(Runtime.getRuntime().
                   availableProcessors()); 
	} 
}

线程有几个状态

public enum State { 
	// 新生 NEW,
	// 运行 RUNNABLE,
    // 阻塞 BLOCKED, 
    // 等待,死死地等 WAITING, 
    // 超时等待 TIMED_WAITING, 
    // 终止 TERMINATED; }

wait/sleep 区别

1、来自不同的类

wait => Object

sleep => Thread

2、关于锁的释放

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

3、使用的范围是不同的

wait:必须在同步代码块中

sleep 可以再任何地方睡

4、是否需要捕获异常

wait 不需要捕获异常

sleep 必须要捕获异常

Synchronized 和 Lock 区别

1、Synchronized 内置的Java关键字, Lock 是一个Java类

2、Synchronized 无法判断获取锁的状态,Lock 可以判断是否获取到了锁

3、Synchronized 会自动释放锁,lock 必须要手动释放锁!如果不释放锁,死锁

4、Synchronized 线程 1(获得锁,阻塞)、线程2(等待,傻傻的等);Lock锁就不一定会等待下

去;

5、Synchronized 可重入锁,不可以中断的,非公平;Lock ,可重入锁,可以 判断锁,非公平(可以

自己设置);

6、Synchronized 适合锁少量的代码同步问题,Lock 适合锁大量的同步代码!

传统 Synchronized

// 基本的卖票例子
public class Demo01 {
    /*** 真正的多线程开发,公司中的开发,降低耦合性 * 线程就是一个单独的资源类,没有任何附属的操作! * 1、 属性、方法 */
    public static void main(String[] args) {
        // 并发:多线程操作同一个资源类, 把资源类丢入线程
        Ticket ticket = new Ticket();
        // @FunctionalInterface 函数式接口,jdk1.8 lambda表达式 (参数)->{ 代码 }
        new Thread(()->{
            for (int i = 1; i < 40 ; i++) { ticket.sale(); }
            },"A").start();
        new Thread(()->{
            for (int i = 1; i < 40 ; i++) { ticket.sale(); }
            },"B").start();
        new Thread(()->{
            for (int i = 1; i < 40 ; i++) { ticket.sale(); }
            },"C").start(); }
        // 资源类 OOP
        static class Ticket {
        // 属性、方法
        private int number = 30;
        // 卖票的方式 // synchronized 本质: 队列,锁
        public synchronized void sale(){
            if (number>0){
                System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票,剩余:"+number); }
        }
    }
}

Lock 接口

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3kzO7KWe-1617262965149)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401102627159.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-486JkDhe-1617262965150)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401102644191.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-r9OTnsmp-1617262965152)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401102650691.png)]

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

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

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo02 {
    public static void main(String[] args) {
        // 并发:多线程操作同一个资源类, 把资源类丢入线程
        Ticket2 ticket = new Ticket2();
        // @FunctionalInterface 函数式接口,jdk1.8 lambda表达式 (参数)->{ 代码 }
        new Thread(()->{
            for (int i = 1; i < 40 ; i++)
                ticket.sale();
            },"A").start();
        new Thread(()->{
            for (int i = 1; i < 40 ; i++)
                ticket.sale();
            },"B").start();
        new Thread(()->{
            for (int i = 1; i < 40 ; i++)
                ticket.sale();
            },"C").start();
    }
}

    // Lock三部曲 //1.new ReentrantLock(); // 2.lock.lock(); // 加锁 // 3.finally=> lock.unlock(); // 解锁
    class Ticket2 {
    // 属性、方法
        private int number = 30;
        Lock lock = new ReentrantLock();
        public 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 版

/*** 线程之间的通信问题:生产者和消费者问题!
 等待唤醒,通知唤醒  线程交替执行 A B 操作同一个变量 num = 0
 A num+1
 B num-1 */
public class Demo03 {
    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){
                //0 // 等待
                this.wait();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            // 通知其他线程,我+1完毕了
            this.notifyAll();
        }
        //-1
        public synchronized void decrement() throws InterruptedException {
            if (number==0){
                // 1
                // 等待
                this.wait();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            // 通知其他线程,我-1完毕了
            this.notifyAll();
        }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cDemyd1S-1617262965153)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401111744934.png)]

if 改为 while 判断(防止虚假唤醒)

/*** 线程之间的通信问题:生产者和消费者问题!
 等待唤醒,通知唤醒  线程交替执行 A B C D操作同一个变量 num = 0
 A num+1
 B num-1
 C num-1
 D num-1*/
public class Demo03 {
    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();
        new Thread(()->{
             for (int i = 0; i < 10; i++) {
                 try {
                     data.decrement();
                 } 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 Data{
        // 数字 资源类
        private int number = 0;
        //+1
        public synchronized void increment() throws InterruptedException {
            while (number!=0){
                //0 // 等待
                this.wait();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            // 通知其他线程,我+1完毕了
            this.notifyAll();
        }
        //-1
        public synchronized void decrement() throws InterruptedException {
            while (number==0){
                // 1
                // 等待
                this.wait();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            // 通知其他线程,我-1完毕了
            this.notifyAll();
        }
}

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GeQza280-1617262965154)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401112458049.png)]

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo04 {
    public static void main(String[] args) {
        Data1 data1 = new Data1();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data1.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data1.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data1.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data1.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}
// 判断等待,业务,通知
class Data1{
    // 数字 资源类
    private int number = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    //condition.await();  等待
    //condition.signalAll();  唤醒全部
    //+1
    public void increment(){
        lock.lock();
        try {
            while (number!=0){
                //0 // 等待
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            // 通知其他线程,我+1完毕了
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    //-1
    public void decrement(){
        lock.lock();
        try {
            while (number==0){
                //0 // 等待
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            // 通知其他线程,我+1完毕了
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

Condition 精准的通知和唤醒线程

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
    A执行完调用B,B执行完调用C,C执行完调用A
*/
public class Demo05 {
    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;//1A 2B 3C
    public void printA(){
        lock.lock();
        try {
            while (num!=1){
                //等待
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>AAAAA");
            //唤醒指定的人
            num = 2;
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printB(){
        lock.lock();
        try {
            while (num!=2){
                //等待
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>BBBBB");
            //唤醒指定的人
            num = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printC(){
        lock.lock();
        try {
            while (num!=3){
                //等待
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>CCCCC");
            //唤醒指定的人
            num = 1;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

8锁现象

如何判断锁的是谁!永远的知道什么锁,锁到底锁的是谁!

1-3

import java.util.concurrent.TimeUnit;

/*
8锁就是关于锁的8个问题
    1.标准情况下,两个线程先打印  1发短信 2打电话
    2.发短信方法延迟4秒,两个线程先打印  1发短信 2打电话
    3.发短信方法延迟4秒,增加了一个普通方法,三个线程先打印  1hello 2发短信 3打电话
*/
public class Demo06 {
    public static void main(String[] args) throws InterruptedException {
        Phone phone = new Phone();
        //锁的存在
        new Thread(()->{
            try {
                phone.sendSms();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            phone.call();
        },"B").start();
        new Thread(()->{
            phone.Hello();
        },"C").start();
    }
}
class Phone{
    //synchronized 锁的对象是方法的调用者
    //两个方法用的是同一个锁,谁先拿到谁先执行
    public synchronized void sendSms() throws InterruptedException {
        TimeUnit.SECONDS.sleep(4);
        System.out.println("发短信");
    }
    public synchronized void call(){
        System.out.println("打电话");
    }
    //这里没有锁,不受锁的影响
    public void Hello(){
        System.out.println("hello");
    }
}

4-8

import java.util.concurrent.TimeUnit;

/*
8锁就是关于锁的8个问题
    4.两个对象,两个同步方法, 1 打电话 2 发短信
    5.增加两个静态的同步方法(一个锁Class模板),只有一个对象,1 发短信 2 打电话
    6.两个对象,两个静态方法(一个锁Class模板) 1 发短信 2 打电话
    7.普通的同步方法和静态的同步方法(一个锁Class模板,一个锁对象),只有一个对象 1 打电话 2 发短信
    8.普通的同步方法和静态的同步方法(一个锁Class模板,一个锁对象),两个对象 1 打电话 2 发短信
*/
public class Demo07{
    public static void main(String[] args) throws InterruptedException {
        //两个对象,两个调用者,两个锁
        Phones phone1 = new Phones();
        Phones phone2 = new Phones();
        //锁的存在
        new Thread(()->{
            try {
                phone1.sendSms();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            phone2.call();
        },"B").start();
    }
}
//Phones只有一个唯一的Class对象
class Phones{
    //synchronized 锁的对象是方法的调用者
    //static 静态方法
    //类一加载就有了,锁的是class
    public static synchronized void sendSms() throws InterruptedException {
        TimeUnit.SECONDS.sleep(4);
        System.out.println("发短信");
    }
    public synchronized void call(){
        System.out.println("打电话");
    }
}

集合类不安全

List不安全

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

//java.util.ConcurrentModificationException 并发修改异常
public class Demo01 {
    public static void main(String[] args) {
        //并发下list不安全
        /*
            解决方案
            1.List<String> list = new Vector<>();  Vector线程安全
            2.List<String> list = Collections.synchronizedList(new ArrayList<>());
            3.List<String> list = new CopyOnWriteArrayList<>();
        */
        //CopyOnWrite 写入是复制 COW 计算机程序设计领域的一种优化策略
        //在写入的时候避免覆盖,造成数据问题
        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();
        }
        //list.forEach(System.out::println);
    }
}

Set不安全

HashSet底层就是HashMap

import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

//java.util.ConcurrentModificationException 并发修改异常
public class Demo02 {
    public static void main(String[] args) {
        //并发下set不安全
        /*
            解决方案
            1.Set<String> set = Collections.synchronizedSet(new HashSet<>());
            2.Set<String> set = new CopyOnWriteArraySet<>();
        */
        //CopyOnWrite 写入是复制 COW 计算机程序设计领域的一种优化策略
        //在写入的时候避免覆盖,造成数据问题
        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();
        }
        //set.forEach(System.out::println);
    }
}

Map不安全

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

//java.util.ConcurrentModificationException 并发修改异常
public class Demo03 {
    public static void main(String[] args) {
        //并发下Map不安全
        /*
            解决方案
            1.Set<String> set = Collections.synchronizedMap(new HashSet<>());
            2.Map<String,String> map = new ConcurrentHashMap<>();
        */
        //map是这样用的吗?  不是,工作中不用HashMap
        //底层是什么?   Map<String,String> map = new HashMap<>(16,0.75);
        //加载因子、初始化容量
        Map<String,String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
        //map.forEach(System.out::println);
    }
}

Collable

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yrnaHKjH-1617262965155)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401135503077.png)]

1、可以有返回值

2、可以抛出异常

3、方法不同,run()/ call()

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Demo04 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //new Thread(new Runnable()).start();
        //new Thread(new FutureTask<>()).start();
        //new Thread(new FutureTask<>(Callable)).start();
        new Thread().start();//怎么启动Callable
        MyThread thread = new MyThread();
        FutureTask futureTask = new FutureTask(thread);//适配类
        new Thread(futureTask,"A").start();
        new Thread(futureTask,"B").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()");//会打印几个call
        //耗时操作
        return 1024;
    }
}

常用的辅助类

CountDownLatch(减法计数器)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-InH5O6gG-1617262965156)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401140711442.png)]

import java.util.concurrent.CountDownLatch;

public class Demo05 {
    public static void main(String[] args) throws InterruptedException {
        //总数是6,必须要执行任务的时候,再使用
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"GO out");
                countDownLatch.countDown();//数量-1
            },String.valueOf(i)).start();
        }
        countDownLatch.await();//等待计数归零,然后再向下执行
        System.out.println("Close Door");
    }
}

CyclicBarrier(加法计数器)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mjt5h29A-1617262965157)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401141410585.png)]

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Demo06 {
    public static void main(String[] args) {
        //集齐7颗龙珠召唤神龙
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
            System.out.println("神龙召唤成功");
        });
        for (int i = 1; i <= 7; i++) {
            //Lambda表达式不能直接操作到i,需要使用一个中间变量
            final int tmp = i;
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"收集了"+tmp+"颗龙珠");
                try {
                    cyclicBarrier.await();//等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

Semaphore(信号量)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PspStF1k-1617262965158)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401142124185.png)]

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class Demo07 {
    public static void main(String[] args) {
        //线程数量:停车位,限流
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                //acquire() 得到
                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();//release()释放
                }
            },String.valueOf(i)).start();
        }
    }
}

ReadWriteLock(读写锁)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LIAt0tfA-1617262965159)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401142808856.png)]

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/*
    独占锁(写锁) 一次只能被一个线程占有
    共享锁(读锁) 多个线程可以同时占有
    ReadWriteLock
    读-读 可以共存
    读-写 不能共存
    写-写 不能共存
*/
public class Demo01 {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        MyCacheLock myCacheLock = new MyCacheLock();
        //写入
        for (int i = 1; i <= 5; i++) {
            final int tmp = i;
            new Thread(()->{
                myCacheLock.put(tmp+"",tmp+"");
            },String.valueOf(i)).start();
        }
        //读取
        for (int i = 1; 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();
    private Lock lock = new ReentrantLock();

    //存,写入的时候,只希望同时只有一个线程写
    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);
            Object o =map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取OK");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            readWriteLock.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");

    }
}

BlockingQueue(阻塞队列)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uRc4oz7w-1617262965160)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401145049300.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9au67rKP-1617262965160)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401145052852.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pjcHM0YR-1617262965160)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401145124171.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ot7Im3wl-1617262965161)(C:\Users\asus\AppData\Roaming\Typora\typora-user-images\image-20210401145135357.png)]

方式抛出异常有返回值,不抛出异常阻塞 等待超时等待
添加addoffer()put()offer(,)
移除removepoll()take()poll(,)
检测队首元素elementpeek--
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/*
BlockingQueue  阻塞队列
*/
public class Demo02 {
    public static void main(String[] args) throws InterruptedException {
        //队列的大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

//        //抛出异常
//        System.out.println(blockingQueue.add("a"));
//        System.out.println(blockingQueue.add("b"));
//        System.out.println(blockingQueue.add("c"));
//        //IllegalStateException: Queue full 抛出异常
//        //System.out.println(blockingQueue.add("d"));
//        System.out.println("==========================");
//        System.out.println(blockingQueue.remove());
//        System.out.println(blockingQueue.remove());
//        System.out.println(blockingQueue.remove());
//        //IllegalStateException: Queue full 抛出异常
//        //System.out.println(blockingQueue.remove());

//        //有返回值,没有异常
//        System.out.println(blockingQueue.offer("a"));
//        System.out.println(blockingQueue.offer("b"));
//        System.out.println(blockingQueue.offer("c"));
//        //System.out.println(blockingQueue.offer("d")); //false 不抛出异常
//        System.out.println("================================");
//        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll());
//        //System.out.println(blockingQueue.poll());//null 不抛出异常

//        //等待,阻塞(一直阻塞)
//        blockingQueue.put("a");
//        blockingQueue.put("b");
//        blockingQueue.put("c");
//        //blockingQueue.put("d");//队列没有位置了,一直阻塞
//        System.out.println("===============================");
//        System.out.println(blockingQueue.take());
//        System.out.println(blockingQueue.take());
//        System.out.println(blockingQueue.take());
//        System.out.println(blockingQueue.take());//没有这个元素,一直阻塞

        //等到,阻塞(等待超时)
        blockingQueue.offer("a");
        blockingQueue.offer("b");
        blockingQueue.offer("c");
        blockingQueue.offer("d",2, TimeUnit.SECONDS);//等待超过2秒就退出
        System.out.println("=======================================");
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        blockingQueue.poll(2,TimeUnit.SECONDS);//等待超过2秒就退出
    }
}

SynchronousQueue (同步队列)

没有容量,放入一个元素就必须等待取出来之后,才能再往里面放一个元素

put,take

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/*
同步队列
不存储元素
put了一个元素,必须从里面take出来后才能再put新元素
*/
public class Demo03 {
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new SynchronousQueue<>();//同步队列
        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName()+"put 1");
                blockingQueue.put("1");
                System.out.println(Thread.currentThread().getName()+"put 2");
                blockingQueue.put("2");
                System.out.println(Thread.currentThread().getName()+"put 3");
                blockingQueue.put("3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T1").start();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+"->"+blockingQueue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+"->"+blockingQueue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+"->"+blockingQueue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T2").start();
    }
}

.getName()+“put 1”);
blockingQueue.put(“1”);
System.out.println(Thread.currentThread().getName()+“put 2”);
blockingQueue.put(“2”);
System.out.println(Thread.currentThread().getName()+“put 3”);
blockingQueue.put(“3”);
} catch (InterruptedException e) {
e.printStackTrace();
}
},“T1”).start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"->"+blockingQueue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"->"+blockingQueue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"->"+blockingQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
},“T2”).start();
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值