生产者消费者实例

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;
}

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值