import java.util.concurrent.*;class Car
{
private boolean waxOn=false;
Object obj=new Object();
public void wax() throws InterruptedException
{
if(!waxOn)
{
System.out.println("wax");
waxOn=true;
obj.notify();
}
else
{
obj.wait();
}
} public void buffer() throws InterruptedException
{
if(waxOn)
{
System.out.println("buffer");
waxOn=false;
obj.notify();
}
else
{
obj.wait();
}
}
}class Wax implements Runnable
{
Car c;
public Wax(Car c)
{
this.c=c;
}
public void run()
{
while(!Thread.interrupted())
{
try
{
c.wax();

}
catch(Exception e)
{
}
} }
}class Buffer implements Runnable
{
Car c;
public Buffer(Car c)
{
this.c=c;
}
public void run()
{
while(!Thread.interrupted())
{
try
{
c.buffer();

}
catch(Exception e)
{
}
}
}
}class Test
{
public static void main(String... args) throws Exception
{
ExecutorService exec=Executors.newCachedThreadPool();
Car c=new Car();
exec.execute(new Buffer(c));
exec.execute(new Wax(c));
try
{
TimeUnit.SECONDS.sleep(5);
}
catch(Exception e)
{
}
exec.shutdownNow();
}
}
请问为什么这个程序可以运行,不适notify和wait方法只能用在同步块内么?

解决方案 »

  1.   

    catch(Exception e)
                {
                }
    为什么不将异常信息记录下来
      

  2.   

    在java类实例或每一个类都一把锁,只有在synchronized 方法或块中当前线程才占有锁,才有锁可以释放。。因此,这wait()和notify()调用必须放置在这样的 synchronized 方法或块中,该方法或块的上锁对象就是调用这一对方法的对象。若不满足这一条件,则程序虽然仍能编译,但在运行时会出现 IllegalMonitorStateException 异常。但你的异常捕获后没有进行任何处理,则会自动忽略,因此才有LZ看到的没有任何错误的"错觉"吧?
      

  3.   

    wait()和notify()调用必须放置在这样的 synchronized 方法或块中