多线程(四)wait()、notify()以及notifyAll()

六、线程得等待和唤醒

1.wait()和notify()的简单示范

public class Wait extends Thread{
    public synchronized  void run()
    {
        System.out.println(getName()+"执行notify()");
        notify();

    }
    public static void main(String []args) {
        Wait w = new Wait();
        synchronized (w){
        try {
            w.start();

            System.out.println(Thread.currentThread().getName() + "等待");
            w.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    }
}
View Code

这程序的流程是main线程被暂停,之后w线程执行notify()方法唤醒main()

猜你喜欢

转载自www.cnblogs.com/lbrs/p/11029443.html