生产者消费者实例

来源:互联网 发布:oracle和mysql的优缺点 编辑:程序博客网 时间:2024/05/29 13:26
package com.cai.Thread.demo;


import java.util.ArrayList;
import java.util.List;


/**
 * 多线程生产消费
 * @author caizl
 *
 */
public class ShengchanXiaofei {
public static void main(String[] args) {
Resource resource=new Resource();
Protuct protuct = new Protuct("生产者", resource);
Customer customer = new Customer("消费着", resource);
protuct.start();
customer.start();
}



}


//生产者类
class Protuct extends Thread{
//生产者生产数量
static int i=0;
//生产者名字
private String name;
//资源
private Resource resource;
//构造函数
public Protuct(String name,Resource resource){
this.name=name;
this.resource=resource;
}
//重写run方法
@Override
public void run() {
while(true){
resource.add(i++);
try {
//为了显示效果休眠100
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("生产者第"+i);
}
}

}
//消费者
class Customer extends Thread{
    //消费者消费数量
static int i=0;
//消费者名字
private String name;
//资源
private Resource resource;
public Customer(String name, Resource resource) {
super();
this.name = name;
this.resource = resource;
}
//重写run方法
@Override
public void run() {
while(true){
try {
//为了显示效果休眠100
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
int n=resource.remove();
System.out.println("消费者::"+n);
}
}

}
//货物资源
class Resource{
//资源库
List<Integer> list = new ArrayList<Integer>();
//假设仓库只能容纳100个
private int total = 100;
//生产者增加资源
public void add(int i){
//同步进行
synchronized (this) {
while(list.size() >= total){//如果仓库中资源数量大于最大容量则停止生产唤醒消费者此时可以消费
try {
this.wait();
} catch (Exception e) {
e.printStackTrace();
}

}
list.add(i);
this.notifyAll();//可以消费了
System.out.println("生产容量"+list.size());
}

}
//消费者消费
public int remove(){
synchronized (this) {
while(list.size() <=0){
try {
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
int i=list.remove(0);
this.notifyAll();//消费之后唤醒生产可以生产
//System.out.println("消费者消费了"+i);
return i;
}

}
}