Wait示例分析

    wait方法使"当前线程"进入阻塞(等待)状态.

 

示例分析:

public class TestWait {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new MyThread("t1");
        synchronized (t){ //main线程持有t对象的锁
            System.err.println(Thread.currentThread().getName() + "... start");
            t.start(); //t被启动后,t执行run里面的方法会阻塞,因为当前线程main持有t对象的锁

            System.err.println(Thread.currentThread().getName() + "... in wait...");
            t.wait(2);//当前main线程进入阻塞(等待)状态,并且线程main释放t的锁,然后main等待notify后重新去竞争t的锁然后继续执行.

            //t对象的锁被释放后,线程t执行run方法的sync会获取到锁然后得到执行,执行完后notify该对象t上面等待的线程main(本例子只有main)
            //主线程main被唤醒,然后重新竞争t对象的锁,得到锁后,继续执行end.
            System.err.println(Thread.currentThread().getName() + "... end");
        }
    }

    static class MyThread  extends Thread {
        public MyThread(String name) {
            super(name);
        }
        @Override
        public void run() {
            synchronized (this){
                for (int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.err.println(Thread.currentThread().getName() + "_exec.."+i);
                }

                System.err.println(Thread.currentThread().getName() + "_ notify....");

                notify();//执行完后notify该对象t上面等待的线程,比如主线程
            }
        }
    }
}

 

posted @ 2018-11-06 17:03  cxyxq  阅读(434)  评论(0编辑  收藏  举报