栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JUC(5)BlockingQueue四组API

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 超时等待

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/680720.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号