package pc;
import java.util.ArrayList;
public class LockObj {
private LockObj(){}
public static LockObj lockObj = new LockObj();
public static ArrayList<String> box = new ArrayList<>();
}
package pc;
public class Producer implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
synchronized (LockObj.lockObj){
if(LockObj.box.size() == 10){
try {
LockObj.lockObj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
LockObj.box.add("产品");
System.out.println("目前产品数: "+ LockObj.box.size());
LockObj.lockObj.notify();
}
}
}
}
package pc;
public class Consumer implements Runnable{
@Override
public void run() {
while(true){
synchronized (LockObj.lockObj){
if(LockObj.box.size() == 0){
try{
LockObj.lockObj.wait();
}catch (Exception e){}
}
LockObj.box.remove("产品");
System.out.println("消费者消费一个产品,剩余:" + LockObj.box.size());
LockObj.lockObj.notify();
}
}
}
}
package pc;
public class Main01 {
public static void main(String[] args) {
new Thread(new Producer()).start();
new Thread(new Consumer()).start();
}
}