JUC(5)BlockingQueue四组API

JUC(5)BlockingQueue四组API,第1张

JUC(5)BlockingQueue四组API 1、读写锁ReadWriteLock

package com.readlock;

import java.util.HashMap;
import java.util.Map;


public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(()->{
              myCache.put(temp+"",temp+"");//写入
            },String.valueOf(i)).start();

        }

        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(()->{
                myCache.get(temp+"");//读取
            },String.valueOf(i)).start();

        }


    }

}

class MyCache{
    private volatile Map 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()+"写入成功");

    }

    //读
    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"读取"+key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取成功");

    }
}

测试结果(正常情况下:写入、写入成功)

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


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

学会使用队列
添加、移除

3、四组API

1、抛出异常

  • 2、不会抛出异常
  • 3、阻塞、等待
  • 4、超时等待
方式抛出异常有返回值,不抛出异常阻塞等待超时等待添加addoffer()put()offer(,)移除removepoll()take()poll(,)判断队列首elementpeek-- 2.1 抛出异常

add 和remove会抛出异常。队列满继续添加数据到队列,队列空,继续取出元素

package com.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;

public class BlockingQueueDemo {
    public static void main(String[] args) {
        test1();
    }

    
    public static void test1(){
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("b"));
        System.out.println(blockingQueue.add("c"));

        
        System.out.println("===========================");
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());

        
        

    }
}

查看队首元素

2.2 不抛出异常

off 和 poll

使用offer不抛出异常

使用poll、源码

2.3 阻塞等待

put 和 take

2.4 超时等待

如果队列满了、设置超时时间、当过了这个超时时间,自动退出

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5681300.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存