专栏首页Android相关Object.wait以及notify注解

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运行结果

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Kotlin---协程(Coroutine)介绍

    线程属于进程,是CPU执行的最小单元。一个进程至少包含一个主线程,也可以拥有多个子线程。线程拥有独立的栈空间。而各个线程共享着进程的代码、内存 、文件FD等。

    None_Ling
  • ReentrantLock加锁与释放过程

    对于公平锁(FairSync)而言在加锁的过程中会有所不同 , 仅仅只是在申请锁的时候 , 加入了队列的判断 , 如果头节点有后继节点的话 , 则让后继节点获取...

    None_Ling
  • ReentrantLock中的NonfairSync加锁流程

    重入锁中的非公平锁,尝试获取锁的线程有可能会成功,如果不成功的话,则会进入AQS的队列中。

    None_Ling
  • 以QQ邮箱为例简说discuz邮箱验证设置

    之前在邮箱设置那困了好久,始终不能使discuz发送邮件验证信息等,直到今天才懂了原因所在,原来之前把端口设错了。

    汐楓
  • python迭代器(函数名的应用,新版格

    s1 = 'asdf' obj = iter(s1) #转化为迭代器 print(obj)#<str_iterator object at 0x000002...

    py3study
  • 20180803_ARTS_week06

    这个是个比较不好的解法,就是像题目介绍里面那样先把这个『之』字形给做出来,然后再逐行读成字符串,但是通过这个比较好帮助我们理解这个题目。

    Bob.Chen
  • 腾讯云提交工单方法教程

    腾讯云如何提交工单?腾讯云遇到问题可以通过控制台的工单系统来解决问题,腾讯云百科分享腾讯云提交工单全过程:

    上云小秘书
  • 机器学习数据预处理:数据降维之PCA

    《实例》阐述算法,通俗易懂,助您对算法的理解达到一个新高度。包含但不限于:经典算法,机器学习,深度学习,LeetCode 题解,Kaggle 实战。期待您的到来...

    double
  • Shell高级用法之重定向绑定

    好了,在有了以上知识的基础上,我们再来看开头提到的>/dev/null 2>&1。这条命令其实分为两命令,一个是>/dev/null,另一个是2>&1。

    院长技术
  • 改进Actor-Critic算法的样本复杂度界(CS LG)

    在强化学习中,actor-critic(AC)算法是一种寻找最优策略的常用方法。AC和natural actor-critic(NAC)算法的有限样本收敛速度是...

    用户7095611

扫码关注云+社区

领取腾讯云代金券