`
BBjava
  • 浏览: 120385 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

线程同步之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());
	}
}





上面的程序编译能通过,但运行时会抛出:
引用
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at org.iteye.bbjava.concurreycy.TestWait.testWaitMethod(TestWait.java:19)
at org.iteye.bbjava.concurreycy.TestWait.main(TestWait.java:29



根椐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的构造方法是第一运行,但事实情况是最后,它们加载顺序是静态块,块,构造方法。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics