/**
* java_解决生产者消费者问题_用最简单的代码
* 库存最大是10,每生产10个开始消费,消费完再生产
*
*/
package 重要练习0922;
public class 生产者消费者问题 {
public static void main(String[] args) {
product p = new product();
new Thread(new Produce(p)).start();
new Thread(new Customer(p)).start();
}
}
class product {
public static int KU_CUN_LIANG_MAX = 10;
public static int xianYouLiang = 0;
public void producer() {
synchronized (this) {
if (this.xianYouLiang >= this.KU_CUN_LIANG_MAX) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.xianYouLiang++;
// 让他生产的快一点
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("生产了第:" + this.xianYouLiang + "件");
if (this.xianYouLiang == this.KU_CUN_LIANG_MAX) {
this.notify();
}
}
}
public void customer() {
synchronized (this) {
if (product.xianYouLiang <= 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费了第:" + this.xianYouLiang + "件");
this.xianYouLiang--;
if (this.xianYouLiang == 0) {
this.notify();
}
}
}
}
class Produce implements Runnable {
product p;
public Produce(product p) {
this.p = p;
}
@Override
public void run() {
while (true) {
p.producer();
}
}
}
class Customer implements Runnable {
product p;
public Customer(product p) {
this.p = p;
}
@Override
public void run() {
while (true) {
p.customer();
}
}
}
java_多线程_解决生产者消费者问题_用最简单的代码
最新推荐文章于 2023-09-01 08:42:34 发布