public class ThreadTest {
/**
- @param args */ public static Integer ticket = 1;
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
for (int i = 0; i < 50; i++)
loopThread(1);
}
}.start();
for (int i = 0; i < 50; i++)
loopThread(0);
}
public static void loopThread(int id) {
// main
synchronized (ticket) {
if (id == ticket && ticket == 0) {
System.out.println("loop 100 times for main thread");
// switch the ticket to sub thread
ticket = 1;
ticket.notify();
} else if (id == ticket && ticket == 1) {
System.out.println("loop 10 times for sub thread");
// switch the ticket to main thread
ticket=0;
ticket.notify();
} else {
try {
ticket.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
求教这个问题错在哪?错误是
loop 10 times for sub thread
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at ThreadTest.loopThread(ThreadTest.java:45)
at ThreadTest$1.run(ThreadTest.java:16)
请不吝赐教,拜谢。。。。