您的位置:首页 > 其它

生产者消费者实例!!!

2017-12-18 11:08 113 查看
本人是小白,只是想留给自己看的,勿喷。。。

生产者类。。。

package aaa;
public class Shengchan implements Runnable {
private Protuct pro=null;
public Protuct getPro() {
return pro;
}
public void setPro(Protuct pro) {
this.pro = pro;
}
public Shengchan(Protuct pro) {
super();
this.pro = pro;
}
public void run() {
for (int i = 0; i < 10; i++) {

try {
pro.shangchan();
} catch (Exception e) {
e.printStackTrace();
}

}
}
}


消费者类。。。

package aaa;
public class xiaofei implements Runnable {
private Protuct pro=null;
public Protuct getPro() {
return pro;
}
public void setPro(Protuct pro) {
this.pro = pro;
}
public xiaofei(Protuct pro) {
super();
this.pro = pro;
}
public void run() {
for (int i = 0; i < 10; i++) {

try {
pro.xiaofei();
} catch (Exception e) {
e.printStackTrace();
}

}
}
}
工厂类

package aaa;

public class Protuct {
private String name;
private int count;
private boolean flag;
public synchronized void shangchan() throws InterruptedException{
if(count==10){
System.out.println("仓库已满");
wait();
}
count++;
Thread.sleep(3000);
System.out.println("生产了一个产品");
notify();
}
public synchronized void xiaofei() throws InterruptedException{
if(count==0){
System.out.println("没有产品,等待生产");
wait();
}
count--;
Thread.sleep(300);
System.out.println("消费了一个产品");
notify();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}


测试类

package aaa;

public class test {
public static void main(String[] args) {
Protuct pro=new Protuct();
Shengchan sheng=new Shengchan(pro);
xiaofei xiao=new xiaofei(pro);
sheng.run();
xiao.run();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  实例