1.效果:
2.代碼:
public class QueueStudy { public static void main(String[] args) { Queue q=new Queue(); PRoducter p=new Producter(q); Customer c=new Customer(q); p.start(); c.start(); }}//生產者class Producter extends Thread{ Queue q; Producter(Queue q){ this.q=q; } public void run(){ for(int i=1;i<6;i++) { q.put(i);//推送數據 } }}//消費者class Customer extends Thread{ Queue q; Customer(Queue q){ this.q=q; } public void run(){ while(true){//循環獲取數據 q.get(); } }}//隊列通知與接收數據class Queue{ int count=0; boolean isEmpty=true; //生產者生產數據 public synchronized void put(int i){ if(!isEmpty){//如果生產者生產的數據不為空,則一直等待,直到數據為空 try{ System.out.println("Product wait ..."); wait(); } catch(Exception e){ e.printStackTrace(); } } count+=i; isEmpty=false; System.out.println("producter totoal product:"+i); notify();//通知消費者數據已生產,請消費數據 } //消費者消費數據 public synchronized void get(){ if(isEmpty){//如果數據為空,消費者等待生產者生產數據,直到有數據為止 try{ System.out.println("Customer wait ..."); System.out.println(""); wait(); } catch(Exception e){ e.printStackTrace(); } } count--; if(count==0){ isEmpty=true; notify();//通知生產者數據已空,請生產者生產數據 } System.out.println("Customer spend :"+count); }}
新聞熱點
疑難解答