您现在的位置是:亿华云 > 热点
A Prototype of Producer-Consumer
亿华云2025-10-03 20:32:24【热点】7人已围观
简介1 Queue.java 1 2 3 4
1 Queue.java
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 package entity; import java.util.ArrayList; import java.util.List; public class Queue { private int maxLen; private List<Integer> list = new ArrayList<Integer>(); public Queue(int maxLen) { this.maxLen = maxLen; } synchronized public void push(Integer value) { try { while (list.size() == maxLen) { this.wait(); } list.add(value); this.notifyAll(); System.out.println(Thread.currentThread().getName() + " push=" + value + ", List=" + list.toString()); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized public Integer pop() { Integer value = null; try { while (list.size() == 0) { this.wait(); } value = list.get(0); list.remove(0); this.notifyAll(); System.out.println(Thread.currentThread().getName() + " pop=" + value + ", List=" + list.toString()); } catch (InterruptedException e) { e.printStackTrace(); } return value; } }2 Producer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package thread; import java.util.Random; import entity.Queue; public class Producer extends Thread { private Queue queue; public Producer(Queue queue) { this.queue = queue; } @Override public void run() { while (true) { Random r = new Random(); int value = r.nextInt(10) + 100; queue.push(value); try { Thread.sleep(r.nextInt(3)*1000); }catch(Exception e){ } } } }3 Consumer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package thread; import java.util.Random; import entity.Queue; public class Consumer extends Thread { private Queue queue; public Consumer(Queue queue) { this.queue = queue; } @Override public void run() { while (true) { queue.pop(); Random r = new Random(); try { Thread.sleep(r.nextInt(3)*1000); }catch(Exception e){ } } } }4 Main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 package app; import entity.Queue; import thread.Consumer; import thread.Producer; public class Main { public static void main(String[] args) throws InterruptedException{ Queue myQueue = new Queue(5); // set the max length of the queue for (int i=0;i<6;i++) { new Producer(myQueue).start(); new Consumer(myQueue).start(); } } }5 snapshot of running
很赞哦!(558)