the code is as follows:
import static java.lang.System.out;
/**
*
*
* @author ***
* @create 2018-11-13 19:48
*/
public class Test0001 {
public static Object OBJ = new Object();
public static int i;
public static class MyThread1 extends Thread {
@Override
public void run() {
while( true ) {
synchronized( OBJ ) {
out.println(Thread.currentThread().getName() + " enter---- " + i);
if( i % 2 == 0 ) {
out.println(Thread.currentThread().getName() + " " + iPP);
try {
out.println(Thread.currentThread().getName() + " wait");
OBJ.wait();
out.println(Thread.currentThread().getName() + " wait over");
} catch( InterruptedException e ) {
e.printStackTrace();
}
} else {
out.println(Thread.currentThread().getName() + " notify");
OBJ.notify();
}
out.println(Thread.currentThread().getName() + "leave--- " + i);
}
}
}
}
public static class MyThread2 extends Thread {
@Override
public void run() {
while( true ) {
synchronized( OBJ ) {
out.println(Thread.currentThread().getName() + " enter---- " + i);
if( i % 2 == 1 ) {
out.println(Thread.currentThread().getName() + " " + iPP);
out.println(Thread.currentThread().getName() + " notify");
OBJ.notify();
} else {
try {
out.println(Thread.currentThread().getName() + " wait");
OBJ.wait();
out.println(Thread.currentThread().getName() + " wait over");
} catch( InterruptedException e ) {
e.printStackTrace();
}
}
out.println(Thread.currentThread().getName() + "leave--- " + i);
}
}
}
}
public static void main( String[] args ) {
Thread t1 = new MyThread1();
Thread t2 = new MyThread2();
t1.start();
try {
Thread.sleep(111);
} catch( InterruptedException e ) {
e.printStackTrace();
}
t2.start();
}
}
the execution result is as follows:
Thread-0 enter---- 0
Thread-0 0
Thread-0 wait
Thread-1 enter---- 1
Thread-1 1
Thread-1 notify
Thread-1leave--- 2 //1
Thread-1 enter---- 2 //2
Thread-1 wait
Thread-0 wait over
Thread-0leave--- 2
Thread-0 enter---- 2
Thread-0 2
Thread-0 wait
then the program gets stuck
curiosity is why Thread-1 immediately enter (statement 2) after Thread-1 leave (statement 1), isn"t it reasonable to Thread-0 enter after Thread-1 leave? Ask for advice!