51,396
社区成员




import java.util.ArrayList;
import java.util.List;
public class FirstThread {
public static void main(String[] args) throws InterruptedException {
List<Object> goods = new ArrayList<>(); //储存物品的仓库,最多储存1
Thread thread1 = new Thread(()->{ //线程1,生产产品
int num = 0;
while(true) {
synchronized (goods) {
if(goods.size()==0) goods.add("商品" + ++num);
else if(goods.size()>0)
try {
goods.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("生产者生产了第"+num+"个产品");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "生产者");
Thread thread2 = new Thread(()->{
int num = 0;
while(true) {
synchronized (goods) {
if(goods.size()>0) goods.remove("商品"+ ++num);
else if (goods.size()==0)
goods.notify();
System.out.println("消费者消费了第"+num+"个产品");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "消费者");
thread1.start();
thread2.start();
}
}