java消息队列
BlockingQueue也是java.util.concurrent下的主要用来控制线程同步的工具。锁也是用来控制线程同步的,释放锁的时候谁拿到了锁是没有预测的,所以谁拿到了锁是不可控的。BlockingQueue消息队列就可以控制。队列是先进先出的。
阻塞:我往队列里面放任务的时候别人不能放,我取任务的时候别人不能取。队列满了就不能put了。
也支持不阻塞队列。
主要的方法是:put、take一对阻塞存取;add、poll一对非阻塞存取。
插入:
1)add(anObject):把任务Runnable加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则抛出异常,不好。
2)offer(anObject):表示如果可能的话,将任务Runnable加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则返回false。尝试放一下,放不进去就等一会再去放。
3)put(anObject):把任务Runnable加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断直到BlockingQueue里面有空间再继续, 有阻塞, 放不进去就等待
读取:
4)poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null; 取不到返回null
5)take():取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到Blocking有新的对象被加入为止; 阻塞, 取不到就一直等
其他
int remainingCapacity();返回队列剩余的容量,在队列插入和获取的时候,不要瞎搞,数 据可能不准, 不能保证数据的准确性,因为有可能队列正在加入或者移除。
boolean remove(Object o); 从队列移除元素,如果存在,即移除一个或者更多,队列改 变了返回true
public boolean contains(Object o); 查看队列是否存在这个元素,存在返回true
int drainTo(Collection<? super E> c); //移除此队列中所有可用的元素,并将它们添加到给定 collection 中。取出放到集合中
int drainTo(Collection<? super E> c, int maxElements); 和上面方法的区别在于,指定了移 动的数量; 取出指定个数放到集合
BlockingQueue有四个具体的实现类,常用的两种实现类为:
1、ArrayBlockingQueue:一个由数组支持的有界阻塞队列,规定大小的BlockingQueue,其构造函数必须带一个int参数来指明其大小.其所含的对象是以FIFO(先入先出)顺序排序的。数组的长度是不可变的。
2、LinkedBlockingQueue:大小不定的BlockingQueue,若其构造函数带一个规定大小的参数,生成的BlockingQueue有大小限制,若不带大小参数,所生成的BlockingQueue的大小由Integer.MAX_VALUE来决定.其所含的对象是以FIFO(先入先出)顺序排序的。
LinkedBlockingQueue 可以指定容量,也可以不指定,不指定的话,默认最大是Integer.MAX_VALUE,其中主要用到put和take方法,put方法在队列满的时候会阻塞直到有队列成员被消费,take方法在队列空的时候会阻塞,直到有队列成员被放进来。
LinkedBlockingQueue和ArrayBlockingQueue区别:
LinkedBlockingQueue和ArrayBlockingQueue比较起来,它们背后所用的数据结构不一样,导致LinkedBlockingQueue的数据吞吐量要大于ArrayBlockingQueue,但在线程数量很大时其性能的可预见性低于ArrayBlockingQueue.
生产者消费者的示例代码:
见代码
package cn.itcast_02_blockingqueue.main;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
//阻塞队列
public class Test {
public static void main(String[] args) throws Exception {
//队列里面随便放什么都可以
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
// BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
// 不设置的话,LinkedBlockingQueue默认大小为Integer.MAX_VALUE
// BlockingQueue<String> queue = new ArrayBlockingQueue<String>(2);
Consumer consumer = new Consumer(queue);
Producer producer = new Producer(queue);
for (int i = 0; i < 3; i++) {
new Thread(producer, "Producer" + (i + 1)).start();
}
for (int i = 0; i < 5; i++) {
new Thread(consumer, "Consumer" + (i + 1)).start();
}
new Thread(producer, "Producer" + (5)).start();
}
}
class Consumer implements Runnable{
BlockingQueue<String> queue;
public Consumer(BlockingQueue<String> queue){
this.queue = queue;
}
@Override
public void run() {
try {
String consumer = Thread.currentThread().getName();
System.out.println(consumer);
String temp = queue.take();//如果队列为空,会阻塞当前线程
System.out.println(consumer+"get a product:"+temp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//一个Runnable就是一个任务,放在一个线程里面执行
/*
class MyThreadWithImpliment implements Runnable
Thread thread1 = new Thread(new MyThreadWithImpliment(1), "thread-1");
thread1.start();
*/
class Producer implements Runnable {
BlockingQueue<String> queue;
public Producer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
System.out.println("I have made a product:"
+ Thread.currentThread().getName());
String temp = "A Product, 生产线程:"
+ Thread.currentThread().getName();
queue.put(temp);//如果队列是满的话,会阻塞当前线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package cn.itcast_02_blockingqueue.main;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class TestBlockingQueue {
public static void main(String[] args) {
//队列里面随便放什么都可以
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
// BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
// 不设置的话,LinkedBlockingQueue默认大小为Integer.MAX_VALUE
// BlockingQueue<String> queue = new ArrayBlockingQueue<String>(2);
TestBlockingQueueConsumer consumer = new TestBlockingQueueConsumer(queue);
TestBlockingQueueProducer producer = new TestBlockingQueueProducer(queue);
for (int i = 0; i < 3; i++) {
new Thread(producer, "Producer" + (i + 1)).start();
}
for (int i = 0; i < 5; i++) {
new Thread(consumer, "Consumer" + (i + 1)).start();
}
new Thread(producer, "Producer" + (5)).start();
}
}
class TestBlockingQueueConsumer implements Runnable{
BlockingQueue<String> queue;
Random random = new Random();
public TestBlockingQueueConsumer(BlockingQueue<String> queue){
this.queue = queue;
}
@Override
public void run() {
try {
Thread.sleep(random.nextInt(10));
System.out.println(Thread.currentThread().getName()+ "trying...");
String temp = queue.take();//如果队列为空,会阻塞当前线程
System.out.println(Thread.currentThread().getName() + " get a job " +temp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class TestBlockingQueueProducer implements Runnable {
BlockingQueue<String> queue;
Random random = new Random();
public TestBlockingQueueProducer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(random.nextInt(10));
String task = Thread.currentThread().getName() + " made a product " + i;
System.out.println(task);
queue.put(task);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}