java解决生产者与消费者问题,Java代码解决生产者---消费者问题

标签:

1.资源

public class Resource {

//当前资源的数量

int num = 0;

//当前资源的上限

int size = 10;

//消费资源

public synchronized void remove() {

//如果num为0,没有资源了,需要等待

while (num == 0) {

try {

System.out.println("消费者进入等待");

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

//如果线程可以执行到这里,说明资源里有资源可以消费

num--;

System.out.println("消费者线程为:" + Thread.currentThread().getName() + "--资源数量:" + num);

this.notifyAll();

}

//生产资源

public synchronized void put() {

//如果资源满了,就进入阻塞状态

while (num == size) {

try {

System.out.println("生产者进入等待");

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

num++;

System.out.println("生产者线程为:" + Thread.currentThread().getName() + "--资源数量:" + num);

this.notifyAll();

}

}

2.消费者

public class Consumer implements Runnable {

private Resource resource;

public Consumer(Resource resource) {

this.resource = resource;

}

@Override

public void run() {

while (true){

resource.remove();

}

}

}

3.生产者

public class Producer implements Runnable {

private Resource resource;

public Producer(Resource resource){

this.resource=resource;

}

@Override

public void run() {

while (true){

resource.put();

}

}

}

4.测试

public class TestConsumerAndProducer {

public static void main(String[] args) {

Resource resource = new Resource();

//生产线程

Producer p1 = new Producer(resource);

//消费线程

Consumer c1 = new Consumer(resource);

new Thread(p1).start();

new Thread(c1).start();

}

}

标签:

来源: https://blog.csdn.net/u010452388/article/details/82624599

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值