Я пытаюсь написать программу-производителя производителя на Java, где производитель вставляет 3 числа в очередь и потребитель, удаляет эти числа из очереди. Я реализовал свою собственную очередь, основанную на моей собственной реализации Linkedlist.Простая потребительская программа Java Threads
Когда я запускаю свой код, мой продюсер заканчивается, но мой потребитель никогда не заканчивается. Я не могу понять, почему
public class ProdConMain {
public static void main(String[] args) throws InterruptedException {
MyQueue queue = new MyQueue();
queue.setLimit(3);
Thread producer = new Thread(new Producer(queue));
Thread consumer = new Thread(new Consumer(queue));
producer.start();
consumer.start();
try {
producer.join();
System.out.println("Producer: " + producer.getState());
consumer.join();
System.out.println("Consumer: " + consumer.getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(queue.list.toString());
}
}
public class Producer implements Runnable {
MyQueue queue = new MyQueue();
Random random = new Random();
public Producer(MyQueue queue) {
this.queue = queue;
}
@Override
public void run() {
int i = 1;
while (i < 10) {
synchronized (queue) {
if (queue.getSize() < queue.getLimit()) {
int value = random.nextInt(500);
queue.enqueue(value);
System.out.println("Inserted: " + value);
queue.notify();
} else {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
i++;
}
}
}
public class Consumer implements Runnable {
MyQueue queue = new MyQueue();
public Consumer(MyQueue queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
if (queue.isEmpty()) {
{
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
int value = queue.dequeue();
System.out.println("Removed: " + value);
queue.notify();
}
}
}
}
}
'Потребитель' никогда не заканчивается, потому что вы используете бесконечный цикл 'while (true)' –