多线程和并发中SynchronousQueue的使用

package javautilconcurrent;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

/**
 * 这是一个阻塞队列,其中,每个插入操作必须等待另一个线程的对应移除操作,反之亦然。
 * 一个同步队列不具有任何内部容量,甚至不具有 1 的容量。
 * 本质上讲,SynchronousQueue 是之前提过的 BlockingQueue 的又一实现。
 * 它给我们提供了在线程之间交换单一元素的极轻量级方法,使用 ArrayBlockingQueue 使用的阻塞语义。
 */
public class SynchronousQueueTest {
 public static void main(String[] args) {
   BlockingQueue drop = new SynchronousQueue();
   (new Thread(new Producer(drop))).start();
   (new Thread(new Consumer(drop))).start();
 }
 
 /**
  *生产者线程
  */
 static class Producer implements Runnable{
  private BlockingQueue drop;
  List messages = Arrays.asList(
    "Mares eat oats",
          "Does eat oats",
          "Little lambs eat ivy",
          "Wouldn't you eat ivy too?");
  public Producer(BlockingQueue drop){
   this.drop = drop;
  }
  public void run(){
   try {
    for(String s : messages){
     System.out.println("Producer:" + System.currentTimeMillis() + " " + s);
     drop.put(s);
    }
    drop.put("DONE");
   } catch (Exception e) {
    System.out.println("Producer Interrupted!");
   }
  }
 }
 
 /**
  * 消费者线程
  */
 static class Consumer implements Runnable{
  private BlockingQueue drop;
  public Consumer(BlockingQueue drop){
   this.drop = drop;
  }
  public void run(){
   try {
    String msg = null;
    while(!((msg = drop.take()).equals("DONE"))){
     System.out.println("Consumer:" + System.currentTimeMillis() + " " + msg);
     Thread.sleep(1000);
    }
   } catch (Exception e) {
    System.out.println("Consumer Interrupted!");
   }
  }
 }
}

结果如下:

Producer:1377436949078 Mares eat oats
Producer:1377436949078 Does eat oats
Consumer:1377436949078 Mares eat oats
Consumer:1377436950078 Does eat oats
Producer:1377436950078 Little lambs eat ivy
Consumer:1377436951078 Little lambs eat ivy
Producer:1377436951078 Wouldn't you eat ivy too?
Consumer:1377436952078 Wouldn't you eat ivy too?

你可能感兴趣的:(多线程&并发)