以前一直没去弄明白synchronized wait notify。从网上查资料得到一点小理解。
例子:图书馆借书,图书馆有一本书,张三借走了,吕四想看也要等张三把书还回来。
1.吕四可以每天去图书馆去看张三是否把书还回来了
public class mytest
{
/**
* 是否把书还回来了
*/
private boolean isreturn = false;
mytest()
{
returnbook();
borrowbook();
}
public boolean borrowbook()
{
while (!isreturn)
{
System.out.println("书还没有还回");
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("书已经还回");
return true;
}
public void returnbook()
{
new Thread()
{
public void run()
{
try
{
System.out.println("书正在使用中....");
Thread.sleep(5000);
System.out.println("书已经看玩");
isreturn = true;
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
public static void main(String[] args)
{
new mytest();
}
}
2.当然上面这种方法是浪费精力的,所以吕四可以等待图书馆张三把书还回的通知
public class mytest
{
/**
* 是否把书还回来了
*/
private boolean isreturn = false;
mytest()
{
returnbook();
borrowbook();
}
public synchronized boolean borrowbook()
{
while (!isreturn)
{
System.out.println("等待书还回的通知....");
try
{
this.wait();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("书已经还回");
return true;
}
public void returnbook()
{
System.out.println("书正在使用中....");
new Thread()
{
public void run()
{
synchronized (mytest.this)
{
try
{
Thread.sleep(5000);
System.out.println("书已经看玩");
isreturn = true;
mytest.this.notify();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
public static void main(String[] args)
{
new mytest();
}
}