wait和notify是用在多线程竞争同一锁资源的情况下使用的。
你这32313133353236313431303231363533e78988e69d8331333335303436段代码实际是个单线程,这个线程自己把自己阻塞了,自然不可能自己把自己唤醒。
你的意图怎么实现呢?需要加入另外一个线程,下面是我仿照你的意图写的一段代码,供参考下
public class A
{
public A(){
final A a = this;
Thread th1 = new Thread(){
@Override
public void run(){
//一直循环,去尝试着唤醒a
try
{
this.sleep(10000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}//为检查是不是能真正实现唤醒a,等待10000毫秒,此时保证a已经处于等待状态中。
while(true){
/**
* 用notify唤醒的线程必须是持有当前锁对象的线程
*/
synchronized (a){
a.notify();
}
}
}
};
th1.setDaemon(true);//这句也是必须的,将th1设为守护线程,保证在唤醒a以后,所有活动的线程都为守护线程,jvm能及时推出
th1.start();//和a.run的顺序不可以换
this.run();
}
public static void main(String[] args)
{
new A();
}
public void run()
{
/**
* 这里可以换成这样,直接锁住this就行了
*/
synchronized (this)
{
try
{
this.wait();//阻塞当前的线程
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
System.out.println("1");//执行finally
}
}
}
}