import java.util.ArrayList;
import java.util.List;
public class Demo7 {
static List<String> list = new ArrayList<>();
static final int MAX_SIZE = 3;//最大容量
//生产者生产产品
public static void product() {
while (true) {
try {
Thread.sleep(600);
synchronized (list) {
if (list.size() >= MAX_SIZE) {
continue;
}
list.add("生产者" + Thread.currentThread().getName() + "-生产的产品");
System.out.println("生产者" + Thread.currentThread().getName() + "-生产产品,当前产品总量:" + list.size());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费者消费产品
public static void consumer() {
while (true) {
try {
Thread.sleep(200);
synchronized (list) {
if (list.size() == 0) {
continue;
}
System.out.println("消费者" + Thread.currentThread().getName() + ",消费产品:" + list.get(0));
list.remove(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
//扮演生产者1
new Thread(() -> {
product();
}).start();
//扮演生产者2
new Thread(() -> {
product();
}).start();
//扮演消费者2
new Thread(new Thread(() -> {
consumer();
})).start();
}
}
简单的多线程,生产者与消费者的关系,生产者数量大于消费者数量
最新推荐文章于 2022-08-21 18:52:40 发布