生产者-消费者模式

多线程模式:生产者-消费者

public class Main {
 
 //数据缓冲区:阻塞队列
 //private static BlockingQueue queue = new LinkedBlockingQueue();
 private static BlockingQueue queue = new ArrayBlockingQueue(10);
// private static BlockingQueue queue = new SynchronousQueue();
 
 static int n =0;

 public static void main(String[] args) {

  Producer p = new Producer("t1", queue);
  p.start();
  Consumer c = new Consumer("t2",queue);
  c.start();
  
  Consumer c2 = new Consumer("t3",queue);
  c2.start();
 }

}

public class Producer extends Thread{
 private BlockingQueue queue;
 
 public Producer(String name,BlockingQueue queue) {
  super(name);
  this.queue = queue;
 }

 public void run() {
  while(true) {
   int num = Main.n++;
   try {
//    Thread.sleep(1000);
    queue.offer(num, 10, TimeUnit.SECONDS);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println("--- " + this.getName() +" " + num);
  }
 }

 
}

public class Consumer extends Thread{
 private BlockingQueue queue;
 
 public Consumer(String name,BlockingQueue queue) {
  super(name);
  this.queue = queue;
 }
 
 public void run() {
  while(true) {
   try {
    Integer s = (Integer)queue.take();
    System.out.println("*** " + this.getName() + " " + s);
    
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }

 
}

猜你喜欢

转载自zw7534313.iteye.com/blog/2416181