/**
* Please note the author longdick at http://longdick.iteye.com
*
*/
wait(), notify(), and notifyAll() are three methods defined in the Object class that can be used to control the state of threads.
All three methods end up calling jvm-level native methods.As the jvm runs on different platforms, it may be slightly different.
- If the object invokes the wait method, the thread holding the object will hand over control of the object and be in a waiting state.
- If an object invokes the notify method, it notifies a thread that is waiting for control of the object to continue running.
- If the object calls the notifyAll method, it will notify all threads waiting for control of the object to continue running.
There are three over load methods for the wait method:
wait()
wait(long)
wait(long,int)
The wait method uses parameters to specify the length of time to wait.If no parameters are specified, by default, wait until notified.
Here is a demonstration code that illustrates complex problems in the most concise way:
Here is a brief description:
NotifyThread is a thread class used to simulate threads that notify other waiting States after 3 seconds;
WaitThread is a thread class used to simulate waiting;
The intermediate object to wait for is flag, a String object;
The main method starts one Notify thread and three wait threads at the same time;
- public class NotifyTest {
- private String flag = "true";
- class NotifyThread extends Thread{
- public NotifyThread(String name) {
- super(name);
- }
- public void run() {
- try {
- sleep(3000);//Delay 3 seconds notification
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- flag = "false";
- flag.notify();
- }
- };
- class WaitThread extends Thread {
- public WaitThread(String name) {
- super(name);
- }
- public void run() {
- while (flag!="false") {
- System.out.println(getName() + " begin waiting!");
- long waitTime = System.currentTimeMillis();
- try {
- flag.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- waitTime = System.currentTimeMillis() - waitTime;
- System.out.println("wait time :"+waitTime);
- }
- System.out.println(getName() + " end waiting!");
- }
- }
- public static void main(String[] args) throws InterruptedException {
- System.out.println("Main Thread Run!");
- NotifyTest test = new NotifyTest();
- NotifyThread notifyThread =test.new NotifyThread("notify01");
- WaitThread waitThread01 = test.new WaitThread("waiter01");
- WaitThread waitThread02 = test.new WaitThread("waiter02");
- WaitThread waitThread03 = test.new WaitThread("waiter03");
- notifyThread.start();
- waitThread01.start();
- waitThread02.start();
- waitThread03.start();
- }
- }
OK, if you take this program and run it, you'll find it doesn't work at all, what happened?Full screen java.lang.IllegalMonitorStateException.
Yes, there are many problems with this program. Let's look at them one by one.
First of all, here are a few facts to note
- At any one time, the object's control (monitor) can only be owned by one thread.
- Whether you execute the wait, notify, or notifyAll method of an object, you must ensure that the currently running thread takes control of the object (monitor)
- If the above three methods of the object are executed in a thread without control, a java.lang.IllegalMonitorStateException exception is reported.
- JVM is multi-threaded and by default it does not guarantee the sequentiality of the runtime threads
Based on these facts, we need to ensure that threads have control of objects.
That is, when executing the wait method in waitThread, make sure that waitThread has control over flag;
When executing the notify method in notifyThread, ensure that notifyThread has control over flag.
Threads take control in three ways:
- Executes a synchronization instance method of the object.
- Executes a synchronous static method for the object's corresponding class.
- Executes a synchronization block with a synchronization lock on the object.
- synchronized (flag) {
- flag = "false";
- flag.notify();
- }
- synchronized (flag) {
- while (flag!="false") {
- System.out.println(getName() + " begin waiting!");
- long waitTime = System.currentTimeMillis();
- try {
- flag.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- waitTime = System.currentTimeMillis() - waitTime;
- System.out.println("wait time :"+waitTime);
- }
- System.out.println(getName() + " end waiting!");
- }
We're a step forward.
Has the problem been solved?
It seems that java.lang.IllegalMonitorStateException is still running or failing.what happened?
The exception at this point is caused by changing the state of the flag object in the synchronization block for the flag object.The following:
flag="false";
flag.notify();
The flag is assigned in the synchronization block so that the object referenced by the flag changes. When the notify method is called again, an exception is thrown because there is no control.
We can improve this by changing flag to a JavaBean and then changing its properties without affecting the reference to flag.
Let's try an array instead, and we can do the same:
- private String flag[] = {"true"};
- synchronized (flag) {
- flag[0] = "false";
- flag.notify();
- }
- synchronized (flag) {
- while (flag[0]!="false") {
- System.out.println(getName() + " begin waiting!");
- long waitTime = System.currentTimeMillis();
- try {
- flag.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
Run again at this time and no exceptions will be reported, but the thread did not end, right, and the thread is blocked and in a wait state.
The simple reason is that we have three wait threads and only one notify thread. When the notify thread runs the notify method, it randomly notifies one waiting thread, so there should be two more waiting threads.
We just need to change the flag.notify() method in the NotifyThread thread class to notifyAll().The notifyAll method notifies all threads waiting for object control.
The final version is as follows:
- public class NotifyTest {
- private String flag[] = { "true" };
- class NotifyThread extends Thread {
- public NotifyThread(String name) {
- super(name);
- }
- public void run() {
- try {
- sleep(3000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- synchronized (flag) {
- flag[0] = "false";
- flag.notifyAll();
- }
- }
- };
- class WaitThread extends Thread {
- public WaitThread(String name) {
- super(name);
- }
- public void run() {
- synchronized (flag) {
- while (flag[0] != "false") {
- System.out.println(getName() + " begin waiting!");
- long waitTime = System.currentTimeMillis();
- try {
- flag.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- waitTime = System.currentTimeMillis() - waitTime;
- System.out.println("wait time :" + waitTime);
- }
- System.out.println(getName() + " end waiting!");
- }
- }
- }
- public static void main(String[] args) throws InterruptedException {
- System.out.println("Main Thread Run!");
- NotifyTest test = new NotifyTest();
- NotifyThread notifyThread = test.new NotifyThread("notify01");
- WaitThread waitThread01 = test.new WaitThread("waiter01");
- WaitThread waitThread02 = test.new WaitThread("waiter02");
- WaitThread waitThread03 = test.new WaitThread("waiter03");
- notifyThread.start();
- waitThread01.start();
- waitThread02.start();
- waitThread03.start();
- }
Reprinted at: https://www.cnblogs.com/leekenky/p/3649829.html