Below is the code:
import java.util.ArrayList; import java.util.List; Public class FirstThread { Public static void main (String [] args) throws InterruptedException { List Goods=new ArrayList<> (a);//store items warehouse, store at most 1 Thread thread1=new Thread (() - & gt; {//thread 1, production product Int num=0; While (true) { Synchronized (goods) { If (goods. The size ()==0) goods. The add (" goods "+ + + num); Else if (goods. The size () & gt; 0) Try { Goods. Wait (); {} catch InterruptedException (e) //TODO Auto - generated the catch block, e.printStackTrace(); } System. The out. Println (" producers produced the first "+ num +" products "); } Try { Thread.sleep(100); {} catch InterruptedException (e) //TODO Auto - generated the catch block, e.printStackTrace(); } } }, "producer"); Thread thread2=new Thread (() - & gt; { Int num=0; While (true) { Synchronized (goods) { If (goods. The size () & gt; 0) goods. Remove (" goods "+ + + num); Else if (goods. The size ()==0) Goods. Notify (); System. The out. Println (" consumer first "+ num +" products "); } Try { Thread.sleep(100); {} catch InterruptedException (e) //TODO Auto - generated the catch block, e.printStackTrace(); } } }, "consumers"); Thread1. Start (); Thread2. Start (); } } Each corresponding num morally only 1 output, but the result is like this would happen
Is there a man can solve, I already know how to get what I want results, just want to know why this is, thank you.