Object.wait以及notify注解

wait()

* Causes the calling thread to wait until another thread calls the {@code
     * notify()} or {@code notifyAll()} method of this object. This method can
     * only be invoked by a thread which owns this object's monitor; see
     * {@link #notify()} on how a thread can become the owner of a monitor.
     * <p>
     * A waiting thread can be sent {@code interrupt()} to cause it to
     * prematurely stop waiting, so {@code wait} should be called in a loop to
     * check that the condition that has been waited for has been met before
     * continuing.
     * <p>
     * While the thread waits, it gives up ownership of this object's monitor.
     * When it is notified (or interrupted), it re-acquires the monitor before
     * it starts running.
     * @throws IllegalMonitorStateException
     *             if the thread calling this method is not the owner of this
     *             object's monitor.
     * @throws InterruptedException
     *             if another thread interrupts this thread while it is waiting.

该方法的注释说:使调用线程处于wait状态,直到其他线程调用这个Object的notify或者notifyAll才会被唤醒。这个方法只能被拥有这个Object的Monitor才能被调用。一个正在wait的线程能够被调用interrupt方法。
当一个线程处于Wait,它放弃了它自己的Object Monitor,当它被notified或者interrupted的时候,它会在它启动之前重新请求这个monitor

noitify()

* Causes a thread which is waiting on this object's monitor (by means of
* calling one of the {@code wait()} methods) to be woken up. If more than one thread is waiting, one of them is chosen at the discretion of the VM. The chosen thread will not run immediately. The thread
     * that called {@code notify()} has to release the object's monitor first.
     * Also, the chosen thread still has to compete against other threads that
     * try to synchronize on the same object.
     * This method can only be invoked by a thread which owns this object's
     * monitor. A thread becomes owner of an object's monitor by executing a synchronized method of that object; by executing the body of a {@code synchronized} statement that synchronizes on the object;by executing a synchronized static method if the object is of type {@code Class}.

使得一个正在等待这个Object的Monitor的线程被唤醒。如果超过一个线程正在等待的话,那么就只有一个线程会被唤醒,而这个线程会由VM自己决定。而这个被选择的线程并不会立马就进入run的状态,调用了notify的线程会首先释放这个Object的Monitor。并且,被选择的线程必须完成和其他线程完成对这个Object锁的竞争。这个方法只能被拥有这个Object的Monitor的线程调用。这个线程拥有这个Object的Monitor,通过执行一个同步方法或者一个同步的代码块来获取这个对象的锁,或者通过执行这个对象的Class类来进行同步。

简单来说,也就是在使用wait和notify的时候,需要使用synchoronized代码块将对象进行Monitor操作,这个操作可以是一个同步代码块,也可以是一个同步的方法,也可以用一个class对象进行同步,总之,在调用wait和notify的时候,必须要进行同步。并且在有多个线程处于wait状态的时候,当调用notify的时候,只有一个线程会收到这个消息,如果是notifyAll的话,所有的线程都会进行竞争,最后也只会有一个线程能够获取到资源,但是它也不会立马进行到run的状态,而是进入就绪的状态,等待时间片到它的时候,就可以执行了。而这个线程的选择是靠JVM来自主决定的。

下面举一个例子:

  1. 错误的例子:使用wait和noitify的时候没有加同步代码块

    public class Test {
    public static void main(String[] args) {
          Object lock = new Object();
          ThreadA threadA = new ThreadA(lock);
          ThreadB threadB = new ThreadB(lock);
          threadA.start();
          threadB.start();
    }
    private static class ThreadA extends Thread {
          Object obj;
    
        public ThreadA(Object lock) {
            obj = lock;
            setName("ThreadA");
        }
    
        @Override
        public void run() {
            super.run();
            System.out.println("Start Wait:" + Thread.currentThread().getName());
            try {
                obj.wait();
            } catch (InterruptedException e) {
            e.printStackTrace();
            }
            System.out.println("Wait End:" + Thread.currentThread().getName());
        }
    }
    
    private static class ThreadB extends Thread {
        Object obj;
    
    public ThreadB(Object lock) {
        obj = lock;
        setName("ThreadB");
    }
    
        @Override
        public void run() {
            super.run();
            System.out.println("ThreadB Start:" + Thread.currentThread().getName());
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException e) {
            }
            System.out.println("After ThreadB Sleep 5S");
            obj.notify();
            System.out.println("ThreadB notify:" + Thread.currentThread().getName());
            }
        }
     }
    

运行后的结果为:

代码1运行结果
  1. 正确使用wait notify的例子:

    public class Test {
        public static void main(String[] args) {
            Object lock = new Object();
            ThreadA threadA = new ThreadA(lock);
            ThreadB threadB = new ThreadB(lock);
            threadA.start();
            threadB.start();
    }
    
    private static class ThreadA extends Thread {
        Object obj;
    
        public ThreadA(Object lock) {
            obj = lock;
            setName("ThreadA");
        }
    
        @Override
        public void run() {
            super.run();
            System.out.println("Start Wait:" + Thread.currentThread().getName());
            try {
                synchronized (obj) {
                    obj.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Wait End:" + Thread.currentThread().getName());
        }
    }
    
        private static class ThreadB extends Thread {
            Object obj;
    
            public ThreadB(Object lock) {
                obj = lock;
                setName("ThreadB");
            }
    
        @Override
        public void run() {
            super.run();
            System.out.println("ThreadB Start:" + Thread.currentThread().getName());
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException e) {
            }
            System.out.println("After ThreadB Sleep 5S");
            synchronized (obj) {
                obj.notify();
            }
            System.out.println("ThreadB notify:" + Thread.currentThread().getName());
            }
        }
    }
    

运行结果:


示例2运行结果

从正确的结果可以看出,在ThreadA和ThreadB同时启动的时候,ThreadB先运行,然后进入了Sleep,后ThreadA运行,打印出了StartWait,然后处于wait状态,等到ThreadB从Sleep5秒醒来后,调用object.notify,并且打印ThreadB notify,于是通知ThreadA,接着ThreadA获取到了Object的Monitor之后,结束运行。

2.错误的例子
让B线程先启动,并且在B线程执行完之后,再继续执行主线程,之后再启动A线程,此时A线程中会调用wait方法,这时候线程A一直在等待notify而导致程序无法正常结束。

public class Test {
public static void main(String[] args) {
    Object lock = new Object();
    ThreadA threadA = new ThreadA(lock);
    ThreadB threadB = new ThreadB(lock);
    threadB.start();
    try {
        threadB.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    threadA.start();
}

private static class ThreadA extends Thread {
    Object obj;

    public ThreadA(Object lock) {
        obj = lock;
        setName("ThreadA");
    }

    @Override
    public void run() {
        super.run();
        System.out.println("Start Wait:" + Thread.currentThread().getName());
        try {
            synchronized (obj) {
                obj.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Wait End:" + Thread.currentThread().getName());
    }
}

private static class ThreadB extends Thread {
    Object obj;

    public ThreadB(Object lock) {
        obj = lock;
        setName("ThreadB");
    }

    @Override
    public void run() {
        super.run();
        System.out.println("ThreadB Start:" + Thread.currentThread().getName());
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
        }
        System.out.println("After ThreadB Sleep 5S");
        synchronized (obj) {
            obj.notify();
        }
        System.out.println("ThreadB notify:" + Thread.currentThread().getName());
    }
}
}
示例2运行结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,884评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,212评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,351评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,412评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,438评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,127评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,714评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,636评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,173评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,264评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,402评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,073评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,763评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,253评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,382评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,749评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,403评论 2 358

推荐阅读更多精彩内容