线程 --生产和消费问题

来源:互联网 发布:java 初始化错误异常 编辑:程序博客网 时间:2024/05/06 05:39
package com.lan;
/**
 * 生产和消费的问题
* @ClassName: ProducerConsumer 
* @Description: TODO
* @author LanHantong
* @date 2011-8-9 下午03:13:39 
*
 */
public class ProducerConsumer {
/**
* @param args
*/
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();

new Thread(c).start();

       }

}
//窝头类
class WoTou{
int id;
WoTou(int id){
     this.id = id;
              }
public String toString(){
return "wotou :" + id;
 }

}
//箩筐类
class SyncStack{
int index = 0;
WoTou[] arrWT = new WoTou[6];
//生产方法
public synchronized void push(WoTou wt){
while(index == arrWT.length ){
try {
//等待
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
      }
     //唤醒其他线程
     this.notify();
    arrWT[index] = wt;
    index++;
}

//消费方法
public synchronized WoTou pop(){
while(index == 0){

  try {

      this.wait();

 } catch (InterruptedException e) {
       e.printStackTrace();
}
     }
     this.notify();
     index--; 
     return arrWT[index];
  }
}




//生产线程
class Producer implements Runnable{
SyncStack ss = null;
//构造方法   持有SyncStack的引用
Producer(SyncStack ss){
this.ss = ss;
}

@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0; i<20; i++){
WoTou wt = new WoTou(i);
ss.push(wt);
System.out.println("生产了,"+wt);
try {
Thread.sleep((int)(Math.random()*200));
} catch (InterruptedException e) {
e.printStackTrace();
   }
}
       }
}
//消费线程
class Consumer implements Runnable{
SyncStack ss = null;
//构造方法   持有SyncStack的引用
Consumer(SyncStack ss){
     this.ss = ss;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0; i<20; i++){
WoTou wt = ss.pop();
System.out.println("消费了,"+wt);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();

}

    }

}

}









原创粉丝点击