当然不会显示Auto Run END了
并且你的程序不能正常结束。因为你的notifyAll();根本就没其任何作用,它不能唤醒autorun线程你的notifyAll();被编译器翻译成 this.notifyAll(); ,它唤醒了以WaitTime类对象做为
监视器的线程,但WaitTime这个线程本身就没有处于wait状态。你的唤醒不起任何作用。要想在WaitTime中唤醒autorun线程,你的WaitTime线程首先要获得autorun线程的锁旗标(就是监视器),然后调用这个监视器的notifyAll(),就可以唤醒autorun线程。而autorun线程是以this作为监视器的,即它本身,所以一个可行的方法是:把autorun对象的this传递给WaitTime线程,并且WaitTime线程的同步代码块也必需以
autorun对象的this作为监视器,然后调用监视器的notifyAll(),即可唤醒autorun线程。
并且你的程序不能正常结束。因为你的notifyAll();根本就没其任何作用,它不能唤醒autorun线程你的notifyAll();被编译器翻译成 this.notifyAll(); ,它唤醒了以WaitTime类对象做为
监视器的线程,但WaitTime这个线程本身就没有处于wait状态。你的唤醒不起任何作用。要想在WaitTime中唤醒autorun线程,你的WaitTime线程首先要获得autorun线程的锁旗标(就是监视器),然后调用这个监视器的notifyAll(),就可以唤醒autorun线程。而autorun线程是以this作为监视器的,即它本身,所以一个可行的方法是:把autorun对象的this传递给WaitTime线程,并且WaitTime线程的同步代码块也必需以
autorun对象的this作为监视器,然后调用监视器的notifyAll(),即可唤醒autorun线程。
public class op extends Thread
{ public op()
{
}
public static void main(String []agrs)
{
new op().start();
} public void run()
{ try
{
synchronized (this)
{
System.out.println("op Run Begin");
WaitTime waitTime = new WaitTime(this);
waitTime.start();
wait(); System.out.println("op Run END"); }
} catch (Exception e)
{
System.out.println(e.getMessage());
} }
}class WaitTime extends Thread
{
boolean b_finished = false;
long i_time = 5000;
op x=null; public WaitTime(op x)
{
this.x=x;
} public void run()
{
synchronized (x)
{
System.out.println("WaitTime Begin"); while (!b_finished)
{
try
{
Thread.sleep(i_time);
x.notifyAll();
b_finished = true;
} catch (Exception e)
{
System.out.println(e.getMessage());
b_finished = true;
} }
System.out.println("WaitTime END");
}
}}