the following code
package liupeng.cn.Algorithm.thread;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadTest {
public static int counter = 0;
public static Integer lock = 0;;
public static void main(String ... arg){
final Semaphore sp = new Semaphore(2);
Thread t1 = new Thread(){
public void run(){
for(int i=0;i<10;iPP){
synchronized (lock) {
try {
while(lock%2==0){
lock.wait();
}
System.out.println("1 "+lock);
lock+=1;
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.notify();
}
}
}
};
Thread t2 = new Thread(){
public void run(){
for(int i=0;i<10;iPP){
synchronized (lock) {
try {
while(lock%2==1){
lock.wait();
}
System.out.println("2 "+lock);
lock+=1;
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.notify();
}
}
}
};
t1.start();
t2.start();
}
}
output error, ask for advice on why this is so, there is nothing wrong with it!
2 0
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at liupeng.cn.Algorithm.thread.ThreadTest$2.run(ThreadTest.java:45)