问题描述
两个进程,生产者和消费者,生产者的作用是生成产品放到共享缓冲区中,消费者的作用是从共享缓冲区消耗产品。重复此过程。
思路
- 生产者生产,当buffer满了就阻塞,没满就+1,并唤醒其他线程。
- 消费者消费,当buffer空了就阻塞,没空就-1,并唤醒其他线程。
- 生产者消费者公用同一把锁。
代码
public class Demo {
public volatile int buffer = 20;
Object object = new Object();
class Producer implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object) {
while (buffer == 20) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer++;
System.out.println(Thread.currentThread().getName() + ": 有" + buffer + "个资源");
object.notifyAll();
}
}
}
}
class Customer implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object) {
while (buffer == 0) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer--;
System.out.println(Thread.currentThread().getName() + ": 有" + buffer + "个资源");
object.notifyAll();
}
}
}
}
public static void main(String[] args) {
Demo demo = new Demo();
for (int i = 0; i <= 5; i++) {
new Thread(demo.new Producer(), "Producer" + i).start();
new Thread(demo.new Customer(), "Customer" + i).start();
}
}
}