线程同步之wait()
下面内容包括内部类实例化,wait()调用,静态块,块,try-catch块语句 会逐一讲一下。
package org.iteye.bbjava.concurreycy;
public class TestWait {
static {
}
public TestWait(){
}
class Apple{
}
public void testWaitMethod(Apple a){
try {
a.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String []args){
TestWait t = new TestWait();
t.testWaitMethod(t.new Apple());
}
}
上面的程序编译能通过,但运行时会抛出:
[color=red]Exception in thread "main"[/color] [color=blue]java.lang.IllegalMonitorStateException[/color] [color=red]at java.lang.Object.wait([/color][color=blue]Native Method[/color]) [color=red]at java.lang.Object.wait([/color][color=blue]Object.java:485[/color]) [color=red]at org.iteye.bbjava.concurreycy.TestWait.testWaitMethod/color [color=red]at org.iteye.bbjava.concurreycy.TestWait.main[/color]([color=blue]TestWait.java:29[/color])
根椐tij4的concurrency部份的内容,调用wait(),notify(),notifyAll()必须使用synchronized块来获得lock,如:
synchronized (a){
a.wait();
}
如你所见,在上面完整代码中的29行是内部类Apple实例化的写法。 完整写法下面改进代码中会出现。
下面将改进代码:
package org.iteye.bbjava.concurreycy;
public class TestWait {
{ System.out.println(" 3 ");}
static {
System.out.println(" 2");
}
public TestWait(){
System.out.println(" 1 ");
}
class Apple{
}
public void testWaitMethod(Apple a){
try {
synchronized (a){
a.wait();
}
System.out.println("testWaitMethod have been called");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void testNotifyMethod(Apple a){
synchronized (a){
a.notify();
}
System.out.println("testWaitMethod have been called");
}
public static void main(String []args){
TestWait t = new TestWait();
Apple a = t.new Apple();
t.testWaitMethod(a);
t.testNotifyMethod(a);
}
}
改进后的代码运行结果:
2 3 1
我期待TestWait的构造方法是第一运行,但事实情况是最后,它们加载顺序是静态块,块,构造方法。