IllegalMonitorStateException в Java

Я получаю IllegalMonitorStateException в моем коде.

внутри startEmployeeProcess() метод я начинаю thread1 (EmployeeThread) и внутри коммутатора я звоню thread1.wait() (случай 3)

В чем проблема в моем коде?

Помощь плз

Спасибо

public class EmployeeManager {

private ArrayList<Employee> employees = new ArrayList<Employee>();
Scanner sc = null;

private  synchronized void startEmployeeProcess(EmployeeManager employeemanager)  {
    System.out
            .println("********************THREAD OBJECT CREATION PROCESS STARTED**************************");
    EmployeeThread employethread = new EmployeeThread(employees);
    Thread thread1 = new Thread(employethread);
    System.out
            .println("********************GOING TO START THE FILE WRITER THREAD******************************");
    thread1.start();
    Scanner sc = new Scanner(System.in);
    do {
        System.out.println("Choose any one option");
        System.out.println("1.Create Employee");
        System.out.println("2.Search Employee by id");
        System.out.println("3.delete Employee by id ");
        System.out.println("4.Print all employee Employee details");
        int choice = sc.nextInt();
        switch (choice) {
        case 1:
            employeemanager.createEmployee();
            break;
        case 2:
            System.out.println("Enter Empid");
            int empId = sc.nextInt();
            employeemanager.searchEmployee(empId);
            break;
        case 3:



                System.out.println("Enter EmpId ");
                try {
                    System.out.println("*************************FILE WRITER THREAD IS IN WAIT PROCESS**********************");
                    thread1.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("***************Deleting*****************");
                int EmpId = sc.nextInt();
                synchronized(employees)
                {
                boolean isEmployeeDeleted = employeemanager.deleteEmployee(EmpId);
                if (isEmployeeDeleted) {
                    System.out.println("Employee is deleted ....!");
                } else {
                    System.out.println("Employee not found");
                }
                System.out.println("*************************FILE WRITER THREAD IS NOTIFIED**********************");
                thread1.notify();
                }
                break;


        case 4:

            employeemanager.printAllEmployeeDetails();

        default:
            System.out.println("wrong choice plz try again....");
            break;

        }
    } while (true);
}

public static void main(String[] args) 
{
    EmployeeManager employeemanager = new EmployeeManager();
    employeemanager.startEmployeeProcess(employeemanager);

}

public void createEmployee() {
    Employee employee = new Employee();
    sc = new Scanner(System.in);
    System.out.println("Enter Employee Name");
    String empName = sc.next();
    System.out.println("Enter employee Id");
    int empId = sc.nextInt();
    System.out.println("Enter employee worklocation");
    String empWorkLocation = sc.next();
    System.out.println("Enter employee Mobile Number");
    int mobNo = sc.nextInt();
    System.out.println("Enter Employee Address");
    String empAddress = sc.next();
    System.out.println("Enter Employee Age");
    int empAge = sc.nextInt();
    employee.setEmpName(empName);
    employee.setEmpId(empId);
    employee.setEmpWorkingLocation(empWorkLocation);
    employee.setEmpMobileNo(mobNo);
    employee.setEmpAddress(empAddress);
    employee.setEmpAge(empAge);
    employees.add(employee);
    System.out.println("employee created ....!");
}

public void searchEmployee(int empId) {
    Iterator<Employee> iterator = employees.iterator();
    while (iterator.hasNext()) {
        Employee employee = (Employee) iterator.next();
        int empid = employee.getEmpId();
        if (empId == empid) {
            System.out.println(employee);
        } else {
            System.out.println("Employee not found");

        }
    }

}

public boolean deleteEmployee(int EmpId) {
    Iterator<Employee> iterator = employees.iterator();
    while (iterator.hasNext()) {
        Employee employee = (Employee) iterator.next();
        int empid = employee.getEmpId();
        if (EmpId == empid) {
            iterator.remove();
            return true;

        }

    }
    return false;
}

public void printAllEmployeeDetails() {
    System.out.println("all employee deatils are ...");
    System.out.println(employees);

}

}

Учебный класс:

EmployeeThread

public class EmployeeThread implements Runnable {
private ArrayList<Employee> employees;

public EmployeeThread(ArrayList<Employee> employees) {
    this.employees = employees;
}

public  void run() {
    try {
        synchronized(employees)
        {

            String filename = "employee.txt";
            FileWriter filewriter = new FileWriter(filename);
            BufferedWriter bufferedwriter = new BufferedWriter(filewriter);
            while (true) {
                for (Employee employee : employees)
                {
                    if (employee.getReadStatus().equalsIgnoreCase("R"))

                    {
                        bufferedwriter.write(employee.toString());
                        employee.setReadStatus("W");
                    }
                }
                employees.wait();
                employees.notify();
            }
            }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();

    }

}
}

1 ответ

Ошибка очевидна:

thread1.wait();
thread1.notify();

Пожалуйста, помните, что вы должны вызывать объект wait() или notify() в синхронизированном блоке того же объекта, который говорит, что вы должны получить блокировку монитора объекта перед вызовом wait() или notify(), например:

synchronized(obj1){
    // obj1.wait();  
    // or obj1.notify();
}

Я думаю, вы должны понимать Java synchronized Ключевое слово ясно, вы можете увидеть этот учебник.

Надеюсь помочь вам.

Другие вопросы по тегам