📄 producerconsumer.java
字号:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package pc;import javax.swing.JTextField;/** * * @author seven */public class ProducerConsumer { public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ProducerConsumerJFrame().setVisible(true); } }); SyncStack ss = new SyncStack(); Producer p = new Producer(ss); Consumer c = new Consumer(ss); new Thread(p).start(); new Thread(c).start(); }}class LV { //产品类 int id; LV(int id) { this.id = id; } public String toString() { return " : " + id; }}class SyncStack { //栈,用来当容器 int index = 0; LV[] arrWT = new LV[5]; JTextField info = null; public void setInfoTextField(JTextField jf){ this.info = jf; } public synchronized void push(LV wt) { //产品入栈(生产) while(index == arrWT.length) { try { info.setText("正在等待消费。。。"); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); arrWT[index] = wt; index ++; if( info != null ){ info.setText( index + " 个产品"); } } public synchronized LV pop() { //产品出栈(消费) while(index == 0) { try { info.setText("正在等待生产。。。"); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } index--; if( info != null ){ info.setText( index + " 个产品"); } this.notify(); return arrWT[index]; }}class Producer implements Runnable { SyncStack ss = null; JTextField info = null; Producer(SyncStack ss) { this.ss = ss; } public void setInfoTextField(JTextField jf){ this.info = jf; } public void run() { for(int i=0; i<20; i++) { LV wt = new LV(i); ss.push(wt);System.out.println("生产了" + wt + "号产品"); if( info != null){ info.setText( wt.id + "号产品"); } try { Thread.sleep((int)(Math.random()*300)); } catch (InterruptedException e) { e.printStackTrace(); } } }}class Consumer implements Runnable { SyncStack ss = null; JTextField info = null; Consumer(SyncStack ss) { this.ss = ss; } public void setInfoTextField(JTextField jf){ this.info = jf; } public void run() { for(int i=0; i<20; i++) { LV wt = ss.pop();System.out.println("消费了" + wt + "号产品"); if( info != null){ info.setText( wt.id + "号产品"); } try { Thread.sleep((int)(Math.random()*800)); } catch (InterruptedException e) { e.printStackTrace(); } } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -