JUC (java.util.concurrent)
集合:
1. PriorityBlockingQueue
是带优先级的无界的阻塞队列,每次出队都返回优先级最高的元素,是二叉树最小堆的实现。
import java.util.concurrent.PriorityBlockingQueue; public class PriorityBlockingQueueTest { public static void main(String[] args) throws Exception{ PriorityBlockingQueue<Customer> queue = new PriorityBlockingQueue<>(); queue.put(new Customer(12)); queue.put(new Customer(42)); queue.put(new Customer(2)); while(!queue.isEmpty()) { System.out.println(queue.take().getAge()); } } } class Customer implements Comparable<Customer> { int age; public Customer (int age) { this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int compareTo(Customer o) { return this.age > o.age ? 1 : -1; } }
运行结果:
2. DelayQueue
阻塞队列, 每个元素都有过期时间,并且队列是个优先级队列,当从队列获取元素时候,只有过期元素才会出队列。
An unbounded {@linkplain BlockingQueue blocking queue} of
* {@code Delayed} elements, in which an element can only be taken
* when its delay has expired.
import lombok.Data; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public class DelayQueueTest extends DelayQueue { public static void main(String[] args) throws Exception { DelayQueue<Item> queue = new DelayQueue<>(); queue.put(new Item("shishi1", 1, TimeUnit.SECONDS)); queue.put(new Item("shishi2", 6, TimeUnit.SECONDS)); queue.put(new Item("shishi3", 4, TimeUnit.SECONDS)); for (int i = 0; i < 3; i++) { Item take = queue.take(); System.out.println(take.getName()); } } } @Data class Item implements Delayed { private long time; private String name; public Item(String name, long time, TimeUnit unit) { this.name = name; this.time = System.currentTimeMillis() + (time > 0 ? unit.toMillis(time) : 0); } @Override public long getDelay(TimeUnit unit) { return this.time - System.currentTimeMillis(); } @Override public int compareTo(Delayed o) { Item item = (Item) o; return this.time <= item.time ? -1 : 1; } @Override public String toString() { return this.name + " : " + this.time; } }
这里会等1,4,6秒超时后依次打印在控制台
3. LinkedBlockingQueue 和 LinkedBlockingDeque
LinkedBlockingQueue单向阻塞队列
LinkedBlockingDeque双向阻塞队列
4. SynchronousQueue
同步队列,阻塞和之前不同,之前的是队列为空或者满才会阻塞,这个是如果入队后没有出队就会阻塞。
所以相当于生产一个消费一个。
5. LinkedTransferQueue
LinkedTransferQueue是一个由链表结构组成的无界阻塞TransferQueue队列。相对于其他阻塞队列,LinkedTransferQueue多了tryTransfer和transfer方法。
LinkedTransferQueue采用一种预占模式。意思就是消费者线程取元素时,如果队列不为空,则直接取走数据,若队列为空,那就生成一个节点(节点元素为null)入队,然后消费者线程被等待在这个节点上,后面生产者线程入队时发现有一个元素为null的节点,生产者线程就不入队了,直接就将元素填充到该节点,并唤醒该节点等待的线程,被唤醒的消费者线程取走元素,从调用的方法返回。我们称这种节点操作为“匹配”方式。
6.ConcurrentHashMap