ClassThreadAextendsThread {Objectoanull; ThreadA (Objecto) {this. oao;} thread A executes the logic publicvoidrun () {thread synchronization region. You need to apply for the public data lock synchronized (oa) {System. out. p
Class ThreadA extends Thread {
// Public data area for Thread Synchronization
Object oa = null;
ThreadA (Object o ){
This. oa = o;
}
// Thread A execution Logic
Public void run (){
// Apply for a public data lock in the thread synchronization Area
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 {
// The current thread waits
Thread. currentThread (). wait ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
} // If (I = 50)
} // For (int I)
}
}
}
/**
* Thread B: Wait for thread A to discard the lock, obtain and execute the lock, and then wake up thread.
*/
Class ThreadB extends Thread {
// Public data area for Thread Synchronization
Object ob = null;
ThreadB (Object o ){
This. ob = o;
}
// Thread B execution Logic
Public void run (){
// Apply for a public data lock in the thread synchronization Area
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 Zone
ThreadA threada = new ThreadA (lock );
ThreadB threadb = new ThreadB (lock );
Threada. start (); // thread A executes
Threadb. start (); // thread B executes
}
} The program is very simple, that is, let threads A and B print alternately. However, two exceptions are thrown during running:
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 lies in Thread. currentThread (). wait (); In ThreadA and running y () in ThreadB.
When beginners understand wait (), they all think it is blocking the current Thread, so Thread. currentThread (). wairt (); it makes sense. But I don't know if you have found that the wait () and notify () methods in the JDK class library are not in the Thread class, but in the Object. Let's take a closer look at the JDK documentation of the wait method:
Public final void wait () throws InterruptedException
Object (Java 2 Platform SE 6)