0
点赞
收藏
分享

微信扫一扫

JUC(5)BlockingQueue四组API


1、读写锁ReadWriteLock

JUC(5)BlockingQueue四组API_java

package com.readlock;

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

/**
* ReadWriteLock
*/
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<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()+"写入成功");

}

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

}
}

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

JUC(5)BlockingQueue四组API_java_02

2、阻塞队列

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

JUC(5)BlockingQueue四组API_抛出异常_03


BlockingQueue

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

学会使用队列
添加、移除

3、四组API

1、抛出异常

  • 2、不会抛出异常
  • 3、阻塞、等待
  • 4、超时等待

方式

抛出异常

有返回值,不抛出异常

阻塞等待

超时等待

添加

add

offer()

put()

offer(,)

移除

remove

poll()

take()

poll(,)

判断队列首

element

peek

-

-

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"));

/**
* 抛出异常:java.lang.IllegalStateException: Queue full
* System.out.println(blockingQueue.add("c"));
*/
System.out.println("===========================");
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());

/**
*取出所有的元素之后、再次取出元素
* java.util.NoSuchElementException
* System.out.println(blockingQueue.remove());
*/


}
}

查看队首元素

JUC(5)BlockingQueue四组API_抛出异常_04

2.2 不抛出异常

off 和 poll

JUC(5)BlockingQueue四组API_阻塞队列_05

使用offer不抛出异常

JUC(5)BlockingQueue四组API_阻塞队列_06

使用poll、源码

JUC(5)BlockingQueue四组API_阻塞队列_07

2.3 阻塞等待

put 和 take

JUC(5)BlockingQueue四组API_抛出异常_08

2.4 超时等待

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

JUC(5)BlockingQueue四组API_抛出异常_09

JUC(5)BlockingQueue四组API_抛出异常_10


举报

相关推荐

0 条评论