Thread waiting and releasing a little Trouble (wait/notify)

Source: Internet
Author: User
Tags documentation thread class

Class Threada extends thread{

Common data area for thread synchronization

Object Oa=null;

Threada (Object o) {

This.oa=o;

}

Thread A execution logic

public void Run () {

Thread synchronization area, requiring a lock for public data

Synchronized (OA) {

System.out.println ("Threada is running ...");

for (int i=0;i<100;i++) {

System.out.println ("Threada value is" +i);

if (i==50) {

try {

Current thread Wait

Thread.CurrentThread (). Wait ();

catch (Interruptedexception e) {

E.printstacktrace ();

}

}//if (I==50)

}//for (int i)

}

}

}

/**

* thread B: Wait for thread A to give up the lock, then get lock and execute, wake thread A when finished

*/

Class Threadb extends thread{

Common data area for thread synchronization

Object Ob=null;

THREADB (Object o) {

This.ob=o;

}

Thread B Execution Logic

public void Run () {

Thread synchronization area, requiring a lock for public data

Synchronized (OB) {

System.out.println ("THREADB is running ...");

for (int i=0;i<50;i++) {

System.out.println ("threadb value is" +i);

}
  

Wake up the waiting thread

Notify ();

}

}

}

Test

public class ThreadTest {

public static void Main (string[] args) {

Object Lock=new object (); Public Data area

Threada threada=new Threada (lock);

THREADB threadb=new threadb (lock);

Threada.start (); Thread A executes

Threadb.start (); Thread B Execution

}

The program is very simple, that is, let the thread a,b alternating printing. But the runtime throws two exceptions:

Exception in thread ' Thread-0 ' java.lang.IllegalMonitorStateException:current thread not owner

Exception in thread ' Thread-1 ' java.lang.IllegalMonitorStateException:current thread not owner

The problem is in the Threada thread.currentthread (). Wait (); and Threadb in the Notify ();

Beginners understand wait () when they think it is blocking the current thread, so Thread.CurrentThread (). Wairt (), depending on the reason. But I do not know if you have found that the wait () and notify () methods in the JDK class library are not in the thread class, but in object (). Let's take a closer look at the JDK documentation for the wait method:

Public final void Wait () throws Interruptedexception

Object (Java 2 Platform SE 6) <!--generated by Javadoc (builds 1.6.0-beta2) on Thu the 21:30:58 CST 2007--> Cript type= "Text/javascript" > Function WindowTitle () {if (location.href.indexOf (' is-external=true ') = = 1) { Parent.document.title=&quot;object (Java 2 Platform SE 6) &quot;; }} </script>

<noscript></noscript>

Causes the current thread to wait before another thread calls the Notify () method or the Notifyall () method of this object. In other words, this method behaves as if it were only executing a wait (0) call.

The current thread must have this object monitor. The thread publishes ownership of this monitor and waits until another thread wakes up by calling the Notify method, or by notifyall the thread waiting on the monitor on this object. The thread will then wait to regain ownership of the monitor before proceeding.

For a version of a parameter, it is possible to implement interrupts and false wakes, and this method should always be used in loops:

Synchronized (obj) {

while (<condition does not hold>)

Obj.wait ();

Perform action appropriate to condition

}

This method should only be invoked by threads that are the owner of this object monitor.

Thrown: illegalmonitorstateexception-If the current thread is not the owner of this object monitor.

Interruptedexception-If any thread interrupts the current thread before the current thread waits for the notification or is waiting for a notification. The interrupt state of the current thread is cleared when this exception is thrown.

After you've read the JDK documentation, it's clear that you just Thread.CurrentThread () the start of the program. Wait (); change to Oa.wait (). Notify (), change to ob.notify () there is no problem.

In other words, the Wait/notify method can only be invoked by synchronizing block obj, not by a thread that is taken for granted. As for why, I have an idea that we can discuss together:

First, we all know that the JVM assigns a unique lock to each object. This lock is in the object.

Then, when the Thread-0 thread obtains this lock, it should record the current own thread number in the lock within the object and set itself to be occupied. So when the Thread-0 need to give up the lock, the lock object will Thread-0 into the lock waiting queue. And all this has nothing to do with Thread-0. Naturally, it is not a Thread-0 object to invoke a method to change a lock in another object (which makes it very clear that my own lock is what you want to change).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.