多线程与阻塞队列

Q.怎么去实现使用独立的进程去生成奇偶数,然后另一个线程打印出奇偶数之和?

A.可以通过多线程以及BlockingQueue来实现。队列是先进先出的数据结构。

 


多线程与阻塞队列
 

 

阻塞队列有以下特性

  1.线程从空队列中获取时,只有在其他线程往队列中放入有效数据后才会返回,否则阻塞  

  2.线程往一个已满队列中放数据时,只有其他线程取出数据腾出空间,或者其他线程清空了队列以后才会添加成功,否则阻塞

 

下面是奇偶数生成类

 

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
  
public class NumberWriter extends Thread {
  
    private  BlockingQueue<Integer> queue;
    private int maxNumber;
    private boolean isEvenNumber;
  
    public NumberWriter(BlockingQueue<Integer> queue, int maxNumber, boolean isEvenNumber) {
        this.queue = queue;
        this.maxNumber = maxNumber;
        this.isEvenNumber = isEvenNumber;
    }
  
    public void run() {
        int i = 1;
        while (i <= maxNumber) {
            try {
                if (isEvenNumber && (i % 2) == 0) {
                 queue.put(i);                        // enqueue
                } else if (!isEvenNumber && i%2 != 0) {
                    queue.put(i);
                }
                ++i;
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }
    }
  
    public static void main(String[] args) {
        final int MAX_NUM = 100;
  
        BlockingQueue<Integer> oddNumberQueue = new ArrayBlockingQueue<Integer>(10);
        BlockingQueue<Integer> evenNumberQueue = new ArrayBlockingQueue<Integer>(10);
  
        NumberWriter oddGen = new NumberWriter(oddNumberQueue, MAX_NUM, false);
        NumberWriter evenGen = new NumberWriter(evenNumberQueue, MAX_NUM, true);
        NumberReceiver receiver = new NumberReceiver(oddNumberQueue, evenNumberQueue);
  
        oddGen.start();
        evenGen.start();
        receiver.start();
  
    }
  
}

 

 

线程会汇总奇偶数之和,然后将结果打印出来

 

import java.util.concurrent.BlockingQueue;
 
public class NumberReceiver extends Thread {
 
 private BlockingQueue<Integer> oddNumberQueue;
 private BlockingQueue<Integer> evenNumberQueue;
 
 public NumberReceiver(BlockingQueue<Integer> oddNumberQueue,
   BlockingQueue<Integer> evenNumberQueue) {
 
  this.oddNumberQueue = oddNumberQueue;
  this.evenNumberQueue = evenNumberQueue;
 
 }
 
 public void run() {
  int odd = 0, even = 0;
 
  try {
   while (odd != -1) {
    odd = oddNumberQueue.take();       //dequeue - FIFO
    even = evenNumberQueue.take();     //dequeue - FIFO
 
    if ((odd + even) % 5 == 0) {
     System.out.println("match found " + odd + " + " + even
       + " = " + (odd + even));
    }
     
   }
 
  } catch (InterruptedException ie) {
   ie.printStackTrace();
   System.exit(1);
  }
 
 }
}

 

 

输出结果:

 

match found 7 + 8 = 15
match found 17 + 18 = 35
match found 27 + 28 = 55
match found 37 + 38 = 75
match found 47 + 48 = 95
match found 57 + 58 = 115
match found 67 + 68 = 135
match found 77 + 78 = 155
match found 87 + 88 = 175
match found 97 + 98 = 195

 

你可能感兴趣的:(阻塞队列)