package jms; import java.util.ArrayList; import java.util.List; public class JmsDemo2 { static final int threadInitNumber = 1; public static void main(String[] args) { Store store = new JmsDemo2().new Store(); List<Thread> producers = new ArrayList<Thread>(); List<Thread> consumers = new ArrayList<Thread>(); for(int i=0;i<threadInitNumber;i++){ producers.add(new Thread(new JmsDemo2().new Producer(store),"【第" + (i+1) +"个生产者】")); consumers.add(new Thread(new JmsDemo2().new Consumer(store),"【第" + (i+1) +"个消费者】")); } for(int i=0;i<threadInitNumber;i++){ producers.get(i).start(); consumers.get(i).start(); } } class Store { private List<String> entry = new ArrayList<String>(); private boolean isProducer = true; public synchronized void push(String msg){ while(isProducer){ entry.add(msg); System.out.println("生产数据" + msg + "等待消费,当前队列深度" + entry.size()); isProducer = false; try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("push end isProducer" + isProducer); } notifyAll(); } public synchronized void get(){ while(!isProducer){ if(entry.isEmpty()){ System.out.println("当前队列为空,等待生产..."); } System.out.println("消费" + entry.remove(entry.size()-1) + "等待生产,当前队列深度" + entry.size()); isProducer = true; try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("get end isProducer" + isProducer); } notifyAll(); } } class Producer implements Runnable{ Store store; public Producer(Store store) { super(); this.store = store; } @Override public void run() { store.push(Thread.currentThread().getName()); } } class Consumer implements Runnable{ Store store; public Consumer(Store store) { super(); this.store = store; } @Override public void run() { store.get(); } } }
Producer &Consumer
猜你喜欢
转载自568025297.iteye.com/blog/2272485
今日推荐
周排行