Извините, если это глупый вопрос, и я забыл некоторые фундаментальные знания c. Я создал проект для решения проблемы потребителя / производителя с помощью потоков. Я использую вектор в качестве буфера и обращаюсь к нему через два отдельных класса для добавления и удаления значений из него. Однако когда я запускаю программу, ничего не происходит? Сначала я думал, что это потому, что я не создал новый объект EmployeeList в классах EmployeeOffice (продюсер) и HeadOffice (потребитель) для доступа к вектору, но я не уверен, где я ошибся. Пожалуйста, смотрите код ниже. Спасибо!
// This is the producer class
public class EmployeeOffice extends EmployeeList {
int value = 0;
final EmployeeList employeeList = new EmployeeList();
public int getValue() {
return value;
}
public void produceEmployee() throws InterruptedException {
while (true) {
synchronized (this) {
while (employeeList.getEmployees().size() == employeeList.getCapacity()) {
wait();
System.out.println("Employee office recruited " + " employee.");
getEmployees().add(value++);
notify();
Thread.sleep(1000);
}
}
}
}
}
// This is the consumer class
public class HeadOffice extends EmployeeList {
public void recieveEmployee() throws InterruptedException{
final EmployeeList employeeList = new EmployeeList();
final EmployeeOffice employeeOffice = new EmployeeOffice();
while (true) {
synchronized (this) {
while (employeeList.getEmployees().size() == 0) {
wait();
int val = employeeList.getEmployees().remove(employeeOffice.getValue());
System.out.println("Head Office recieved " + val + " employee");
notify();
Thread.sleep(1000);
}
}
}
}
}
import java.util.Vector;
public class EmployeeList {
Vector<Integer> employees = new Vector<>();
int capacity = 5;
public int getCapacity() {
return capacity;
}
public Vector<Integer> getEmployees() {
return employees;
}
}
public class Server{
public static void main(String[] args) throws InterruptedException {
final EmployeeOffice employeeOffice = new EmployeeOffice();
final HeadOffice headOffice = new HeadOffice();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
employeeOffice.produceEmployee();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try{
headOffice.recieveEmployee();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
}