- package ProductConsumer;
- import org.ietf.jgss.Oid;
- public class Test {
- public static void main(String[] args){
- Market mt=new Market();
- Product product=new Product(mt);
- Consumer consumer=new Consumer(mt);
- new Thread(product).start();
- new Thread(consumer).start();
- }
- }
- class Product implements Runnable{
- Market market=null;
- public Product(Market mt){
- this.market=mt;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- for(int i = 0; i < 20; i++) {
- WoTou wt=new WoTou(i);
- market.push(wt);
- System.out.println("生產了:"+wt);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- class Consumer implements Runnable{
- Market market=null;
- public Consumer(Market mt){
- this.market=mt;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- for(int i = 0; i < 60; i++) {
- /*WoTou wt=new WoTou(i);
- market.push(wt);*/
- WoTou wTou=market.pop();
- System.out.println("消費了:"+wTou);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- class Market {
- WoTou[] wtArr=new WoTou[6];
- int index=0;
- public synchronized void push(WoTou wt){
- wtArr[index]=wt;
- index++;
- while(index==wtArr.length) {
- try {
- this.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- this.notify();
- }
- public synchronized WoTou pop(){
- while (index==0) {
- try {
- this.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- this.notify();
- index--;
- return wtArr[index];
- }
- }
- class WoTou{
- int id;
- public WoTou(int id){
- this.id=id;
- }
- @Override
- public String toString() {
- // TODO Auto-generated method stub
- return "WOTUO:"+id;
- }
- }