1.阻塞队列:是线程安全的
队列满后,如果没有消费者消费队列,那么生存者会阻塞,除非通过
blockingQueue.offer("an apple",5,TimeUnit.SECONDS);//队列满了,指定时间后,不再阻塞
对列空了,如果没有生产者生产队列,那么消费者会阻塞,除非通过
blockingQueue.poll(1, TimeUnit.SECONDS); //队列空时,指定阻塞时间后返回,不会一直阻塞
public class BlockQueueDemo {
private static BlockingQueue blockingQueue = new LinkedBlockingDeque(2);//使用了CAS,lock以及lock.condition的await(),signal() 有两个condition
static class Producer implements Runnable {
private String name;
public Producer(String name) {
this.name = name;
}
public void run() {
try {
System.out.println(name + " start produce");
blockingQueue.put("an apple");
// blockingQueue.offer("an apple",5,TimeUnit.SECONDS);//队列满了,指定时间后,不再阻塞
System.out.println(name + " end produce");
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
//To change body of implemented methods use File | Settings | File Templates.
}
}
static class Consumer implements Runnable {
private String name;
public Consumer(String name) {
this.name = name;
}
public void run() {
try {
System.out.println(name + " start consumer");
// blockingQueue.take(); //队列空了,会一直阻塞,
blockingQueue.poll(1, TimeUnit.SECONDS); //队列空时,指定阻塞时间后返回,不会一直阻塞
System.out.println(name + " end consumer");
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
public static void main(String[] args) {
Producer producer1 = new Producer("producer1");
Producer producer2 = new Producer("producer2");
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(producer1);
executorService.submit(producer2);
executorService.submit(producer1);
Consumer consumer = new Consumer("consumer1");
executorService.submit(consumer);
}
}
2.非阻塞队列:是线程安全的
public class NoBlockQueue {
private static ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<Integer>();//使用了CAS原语
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(new Producer("producer1"));
executorService.submit(new Producer("producer2"));
executorService.submit(new Producer("producer3"));
executorService.submit(new Consumer("consumer1"));
}
static class Producer implements Runnable {
private String name;
public Producer(String name) {
this.name = name;
}
public void run() {
for (int i = 1; i < 10; ++i) {
System.out.println(name+ " start producer " + i);
concurrentLinkedQueue.add(i);
System.out.println(name+"end producer " + i);
}
}
}
static class Consumer implements Runnable {
private String name;
public Consumer(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 10; ++i) {
System.out.println(name+" start Consumer " + i);
System.out.println(concurrentLinkedQueue.poll());
System.out.println(name+" end Consumer " + i);
}
}
}
}