public class Main {
public static void main(String[] args) throws InterruptedException {
Produce p = new Produce();
new Thread(new Runnable() {
@Override
public void run() {
new Consume(p);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
new Product(p);
}
}).start();
Thread.sleep(10000);
}
}
class Consume {
Produce p;
public Consume(Produce p) {
this.p = p;
while (true) {
try {
p.consumeProduce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Product {
Produce p;
public Product(Produce p) {
this.p = p;
while (true) {
try {
p.productProduce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Produce {
int m = 0;
public synchronized void consumeProduce() throws InterruptedException {
if (m <= 0) {
notifyAll();
this.wait();
}
m--;
Thread.sleep(800);
System.out.println(Thread.currentThread().getName() + "消费了-->" + m);
}
public synchronized void productProduce() throws InterruptedException {
m += 10;
System.out.println(Thread.currentThread().getName() + "生产-->" + m);
notifyAll();
this.wait();
}
}
生产者消费者
最新推荐文章于 2023-04-26 09:27:27 发布