下面是代碼:
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();
}
}
按理來說每個對應的num只有一句輸出,但是結果卻會出現下面這樣的情況

有沒有好心人能解答一下,我已經知道怎么能得到我想要的結果,只是單純想知道這是為什么,謝謝。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/281839.html
標籤:Java相關
上一篇:Java
下一篇:批量下載
