1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| public class BlockingQueueTests {
public static void main(String[] args) { BlockingQueue queue = new ArrayBlockingQueue(10); new Thread(new Producer(queue)).start(); new Thread(new Consumer(queue)).start(); new Thread(new Consumer(queue)).start(); new Thread(new Consumer(queue)).start(); } }
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) { this.queue = queue; }
@Override public void run() { try { for (int i = 0; i < 100; i++) { Thread.sleep(20); queue.put(i); System.out.println(Thread.currentThread().getName() + "生产:" + queue.size()); } } catch (Exception e) { e.printStackTrace(); } } }
class Consumer implements Runnable {
private BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) { this.queue = queue; }
@Override public void run() { try { while (true) { Thread.sleep(new Random().nextInt(1000)); queue.take(); System.out.println(Thread.currentThread().getName() + "消费:" + queue.size()); } } catch (Exception e) { e.printStackTrace(); } } }
|