我對線程很陌生,只是想掌握基礎知識。我正在嘗試解決消費者-生產者問題。任何人都可以幫助我的代碼。import java.util.ArrayList;import java.util.List;public class T{ public static void main(String[] args) { ConsumeProduce consumeproduce = new ConsumeProduce(); C c=new C(); P p=new P(); c.start(); p.start(); consumeproduce.printList(); }}class C extends Thread{ public void run() { ConsumeProduce consumeproduce =new ConsumeProduce(); try { consumeproduce.consume(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}class P extends Thread{ public void run() { ConsumeProduce consumeproduce =new ConsumeProduce(); try { consumeproduce.produce(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}class ConsumeProduce{ static int i=5; public List list =new ArrayList<>(10); synchronized void consume() throws InterruptedException { while(i>0) { wait(); list.remove(i); System.out.println("removed"+i); i--; notifyAll(); } } synchronized void produce() throws InterruptedException { while(i<=10) { wait(); i++; list.add(i, 1); System.out.println("added"+i); notifyAll(); } } void printList() { for (Object i:list) { System.out.println(i); } }}我無法弄清楚我的代碼有什么問題。任何形式的幫助都會很有用
使用多線程的消費者-生產者問題
幕布斯6054654
2021-12-01 16:50:45
