package com.zfy.learn;
public class ProductorAndCostumer {
public static void main(String[] args) {
Channel channel = new Channel();
new Thread(
()->new Productors(channel).run()
).start();
new Thread(
()->new Costumers(channel).run()
).start();
}
}
class Productors implements Runnable{
Channel channel;
public Productors(Channel channel) {
this.channel = channel;
}
@Override
public void run() {
for (int i = 1; i <100 ; i++) {
System.out.println("生产编号为"+i+ "的产品");
try {
this.channel.produce(new Product(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Costumers implements Runnable{
Channel channel;
public Costumers(Channel channel) {
this.channel = channel;
}
@Override
public void run() {
for (int i = 1; i <100 ; i++) {
try {
System.out.println( "消费产品编号:" +this.channel.cost().getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Channel{
Product[] prdts = new Product[10];
int count =0 ;//计数器
public synchronized void produce(Product p) throws InterruptedException {
if(count == prdts.length)
this.wait();
prdts[count++] = p;
this.notifyAll();
}
public synchronized Product cost() throws InterruptedException {
if(count == 0)
this.wait();
count--;
this.notifyAll();
return prdts[count];
}
public Channel() {
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
class Product{
int id;
public Product(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
生产者消费者问题
最新推荐文章于 2023-06-21 10:25:03 发布