Note that there are some explanatory texts on larger screens.

plurals
  1. POUnderstanding the use of Synchronized
    primarykey
    data
    text
    <p>I am trying to understand the use of Synchronized block. </p> <p>In the below program, Inside a produce and consumer method I have created a synchronized block and if I lock it by using lock1(object). I am getting the following error, why is this, why am i getting this error? </p> <p>I am aware that by replacing lock1 by this(same class). I can get rid of the error. I still want to know why this error as everything seems very logical to me.</p> <p>Program</p> <pre><code>import java.util.Scanner; public class Worker { private Object lock1 = new Object(); private Object lock2 = new Object(); public void produce() throws InterruptedException { synchronized (lock1) { System.out.println("Producer thread running"); wait(); System.out.println("Producer resumed"); } } public void consumer() throws InterruptedException { Scanner scanner = new Scanner(System.in); Thread.sleep(2000); synchronized (lock1) { System.out.println("Waiting for return key"); scanner.nextLine(); System.out.println("return key is pressed"); notify(); Thread.sleep(5000); System.out.println("Consumer is over"); } } public void main() { Thread t1 = new Thread(new Runnable() { public void run() { try { produce(); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread t2 = new Thread(new Runnable() { public void run() { try { consumer(); } catch (InterruptedException e) { e.printStackTrace(); } } }); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } </code></pre> <p><p></p> <pre><code>Exception in thread "Thread-0" java.lang.IllegalMonitorStateException at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:503) at Worker.produce(Worker.java:14) at Worker$1.run(Worker.java:43) at java.lang.Thread.run(Unknown Source) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload