package org.tuyifei.dao;
import java.util.LinkedList;
public class Container {
private static final LinkedList<String> disk = new LinkedList<>();
private static byte[] b = new byte[0];
private static int max = 10;
Object o = new Object();
public void put(String food) {
if(disk.size()<=max){
System.out.println("生产者生产:"+food);
synchronized (disk) {
// 因为LinkList线程不安全,就是添加了可能size也变了但是没存储进去
disk.add(food);
try {
synchronized (b) {
// 唤醒所有消费者,如果要加队列上线,再重新建个锁挂到上面,等待消费者唤醒
b.notifyAll();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void eat(){
if(disk.size()!=0){
System.out.println("消费者吃了"+disk.getLast());
synchronized (disk) {
disk.removeLast();
}
}else{
synchronized (b) {
try {
// 如果没资源消费者等待
b.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
package org.tuyifei.dao;
import java.util.Random;
public class Test01 {
public static void main(String[] args) {
new Thread(new Cooker()).start();
new Thread(new Customer()).start();
new Thread(new Customer()).start();
new Thread(new Customer()).start();
new Thread(new Customer()).start();
new Thread(new Customer()).start();
new Thread(new Customer()).start();
new Thread(new Customer()).start();
}
}
class Cooker implements Runnable{
private static final String[] food = {"砒霜","农药","吸铁石","炸药","水泥"};
public static void make(){
// 创建一个随机食物
new Container().put(food[new Random().nextInt(food.length)]);
}
@Override
public void run() {
while (true) {
make();
}
}
}
class Customer implements Runnable{
@Override
public void run() {
while (true) {
new Container().eat();
}
}
}
package org.tuyifei.dao;import java.util.LinkedList;public class Container { private static final LinkedList disk = new LinkedList<>(); private static byte[] b = new byte[0]; private static int