I am trying to learn Multi threading and for practice, I am trying to print odd & even number using two thread. I have created an object which will act as a lock for the both the threads. When I try to execute it throws java.lang.IllegalMonitorStateException
.
class EVENODDimpl implements Runnable {
int num;
int temp = 0;
Object lock = new Object();
public EVENODDimpl( int num) {
this.num = num;
}
public void run() {
try {
synchronized (lock) {
while(temp<num) {
temp++;
System.out.println(Thread.currentThread().getName()+" "+temp);
this.notify();
this.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Main Method:
public class EVENODD {
public static void main(String[] args) {
int i = 10;
EVENODDimpl ei = new EVENODDimpl(i);
Thread t1 = new Thread( ei,"EvenThread");
Thread t2 = new Thread( ei,"OddThread");
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
To print alternate pages of a PDF with Adobe Acrobat Reader, click on Print and find the Pages to Print section. Click on More Options and choose whether you want to print even pages or odd pages.
This behavior occurs when you include page numbers that are numbered differently than the physical pages in the document (for example, when the first page of your document is defined as page 2, the second page is defined as page 3, and so on).
Choose File > Print and select Odd Pages Only from the Subset menu. (Do not select Reverse Pages this time.) Click OK or Print.
You wait
and notify
on this
, but you should wait
and notify
on lock
because you synchronize on lock
, you can't wait
and notify
on other object than the one on which you're synchronizing, working version:
class EVENODDimpl implements Runnable {
int num;
int temp = 0;
Object lock = new Object();
public EVENODDimpl( int num) {
this.num = num;
}
public void run() {
try {
synchronized (lock) {
while(temp<num) {
temp++;
System.out.println(Thread.currentThread().getName()+" "+temp);
lock.notify();
lock.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
As it said from the javadoc
Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.
This means that your methods notify
and wait
should own monitor. Or in other words the object that is calling these method must be synchronized. Your this
object is not synchronized. That's why you get this exception. Call this method from lock
object in your case.
Your logic is still wrong but it is up to you to explore that.
java.lang.IllegalMonitorStateException
Exception occur because you are using notify method on the object this.notify()
but that Object is not synchronized.
Replace synchronized (lock)
with this: synchronized (this)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With