lundi 7 décembre 2020

getting IllegalMonitorStateException error for the implementation of producer - consumber patterns

Got ‘IllegalMonitorStateException’ error, Error appears when using synchronized keywords to implement producer/consumer mode, any suggestion? I understand without synchronized code block will cause this error

public class Test7 {
   
    class Producer implements Runnable{

        @Override
        public void run() {

                while (flag)
                {
                    synchronized (LOCK)
                    {
                        if (count <=FULL-1)
                        {
                            System.out.println("producer " + Thread.currentThread().getName() + " total " + ++count + " resources");
                            LOCK.notifyAll();
                        }else{
                            try {
                                flag = !flag;
                                wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
        }
    }
    class Consumer implements Runnable{

        @Override
        public void run() {

                while (!flag)
                {
                    synchronized (LOCK){
                        if (count > 0)
                        {
                            System.out.println("consumer " + Thread.currentThread().getName() + " total " + --count + " resources");
                            LOCK.notifyAll();
                        }
                        else
                        {
                            try {
                                flag = !flag;
                                wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
        }
    }
}

The error message:

Aucun commentaire:

Enregistrer un commentaire