我对线程很陌生,只是想掌握基础知识。我正在尝试解决消费者-生产者问题。
任何人都可以帮助我的代码。
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);
}
}
}
我无法弄清楚我的代码有什么问题。任何形式的帮助都会很有用
蝴蝶刀刀
相关分类