java中使用wait就得使用同步锁,而且2个线程必须都使用同步代码块,否则就会异常

时间:2015-08-27 09:29:14   收藏:0   阅读:310

标题已经说明,子线程wai()时候默认的锁不是同步代码块的锁,因此wai时候显示的指明锁,现在解释看code:

public class Test {
//	static	boolean flag=true;
	public static void main(String[] args) throws InterruptedException {
	
		Zp z=new Zp();
		Thread st=new Thread(z);
		st.start();
		for(int x=0;x<100000;x++)
		{
			if(x%5000==0)
			{
//				flag=false;
				Thread.sleep(3000);
				synchronized (Test.class) //这里必须判断同步,否则当子线程没有放弃锁的时候,就执行下面会出现异常
				{
					Test.class.notify();
				}
				
			}
		}
		
	}
static class Zp implements Runnable
{
	@Override
	public void run() {
	
		synchronized (Test.class) {
			while(true)
			{
			for(int x=0;x<10;x++)
			{
			System.out.println("haha...");
			}
			
					try {
						Test.class.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
			}
		}
	}
	
}

}

  

原文:http://www.cnblogs.com/bokeofzp/p/4762248.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!