Java线程相关方法之Object篇

isen
isen
发布于 2023-09-23 / 86 阅读 / 0 评论 / 0 点赞

Java线程相关方法之Object篇

一、Ojbect 的方法简介

wait、notify、notifyAll方法进行同步的关键是对象锁,对象锁将它们进行关联起来。

1、wait

让当前线程(调用 wait 的线程)进行等待状态,并且让当前线程释放持有的对象锁(即 wait 方法的所属对象)。

wait() 方法的部分javadoc说明

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

特别注意:调用 wait 的线程需要先获取 wait 方法所属对象的对象锁。

获取对象锁的方法有:

1. synchronized 对象的实例方法

2. synchronized 对象的对象中的语句块

3. synchronized 对象的静态方法

当线程调用 wait 后处于等待状态,可能由于其他线程的 interrupt 或者假唤醒,所以 wait 的正确使用方式是:

synchronized (obj) {

    while (<condition does not hold>)

        obj.wait();//可能会跑出运行时异常,如果有需要,进行try

    ... // Perform action appropriate to condition

    }
}

2、notify

唤醒一个在等待获取对象锁(即 notify 方法所属的对象)的线程。

特别注意:调用 notify 的线程需要先获取 notify 方法所属对象的对象锁。

3、notifyAll

唤醒所有在等待获取对象锁(即 notifyAll 方法所属的对象)的线程。

特别注意:调用 notifyAll 的线程需要先获取 notifyAll 方法所属对象的对象锁。

wait、notify、notifyAll协作的示例

public class ObjectDemo {

    private static Object monitor = new Object();

    private static volatile boolean condition = false;

    static class MyThread extends Thread{

        @Override

        public void run() {

            synchronized (monitor){

                System.out.println(this.getName() + " MyThread run 获取得锁monitor");

                while (!condition){

                    try {

                        System.out.println(this.getName() + " MyThread run 调用wait,释放锁monitor,并且进入等待状态");

                        monitor.wait();

                        System.out.println(this.getName() + " MyThread run 重新获取锁获取得锁monitor");

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

                System.out.println(this.getName() + " MyThread run 处理剩余业务逻辑");

                //根据实际需要,调用一下notify或者notifyAll

            }

        }

    }

    static class MyThread2 extends Thread{

        @Override

        public void run() {

            synchronized (monitor){

                System.out.println(this.getName() + " MyThread2 run 获取得锁monitor,并处理业务逻辑");

                System.out.println(this.getName() + " 设置condition为true,调用notify, 唤醒一个等待线程");

                condition = true;

                monitor.notify();

//                System.out.println(this.getName() + " 处理完业务逻辑,调用notifyAll, 唤醒所有等待线程");

//                monitor.notifyAll();

                System.out.println(this.getName() + " 只有程序退出该同步块,被唤醒的线程,才有可能获取锁monitor");

            }

        }

    }

    public static void main(String[] args) {

        new MyThread().start();

        new MyThread().start();

        new MyThread2().start();

    }

}

二、Object 的方法源码

public class Object {

    /**

     * Causes the current thread to wait until either another thread invokes the

     * {@link java.lang.Object#notify()} method or the

     * {@link java.lang.Object#notifyAll()} method for this object, or a

     * specified amount of time has elapsed.

     * <p>

     * The current thread must own this object's monitor.

     * <p>

     * This method causes the current thread (call it <var>T</var>) to

     * place itself in the wait set for this object and then to relinquish

     * any and all synchronization claims on this object. Thread <var>T</var>

     * becomes disabled for thread scheduling purposes and lies dormant

     * until one of four things happens:

     * <ul>

     * <li>Some other thread invokes the {@code notify} method for this

     * object and thread <var>T</var> happens to be arbitrarily chosen as

     * the thread to be awakened.

     * <li>Some other thread invokes the {@code notifyAll} method for this

     * object.

     * <li>Some other thread {@linkplain Thread#interrupt() interrupts}

     * thread <var>T</var>.

     * <li>The specified amount of real time has elapsed, more or less.  If

     * {@code timeout} is zero, however, then real time is not taken into

     * consideration and the thread simply waits until notified.

     * </ul>

     * The thread <var>T</var> is then removed from the wait set for this

     * object and re-enabled for thread scheduling. It then competes in the

     * usual manner with other threads for the right to synchronize on the

     * object; once it has gained control of the object, all its

     * synchronization claims on the object are restored to the status quo

     * ante - that is, to the situation as of the time that the {@code wait}

     * method was invoked. Thread <var>T</var> then returns from the

     * invocation of the {@code wait} method. Thus, on return from the

     * {@code wait} method, the synchronization state of the object and of

     * thread {@code T} is exactly as it was when the {@code wait} method

     * was invoked.

     * <p>

     * A thread can also wake up without being notified, interrupted, or

     * timing out, a so-called <i>spurious wakeup</i>.  While this will rarely

     * occur in practice, applications must guard against it by testing for

     * the condition that should have caused the thread to be awakened, and

     * continuing to wait if the condition is not satisfied.  In other words,

     * waits should always occur in loops, like this one:

     * <pre>

     *     synchronized (obj) {

     *         while (&lt;condition does not hold&gt;)

     *             obj.wait(timeout);

     *         ... // Perform action appropriate to condition

     *     }

     * </pre>

     * (For more information on this topic, see Section 3.2.3 in Doug Lea's

     * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley,

     * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming

     * Language Guide" (Addison-Wesley, 2001).

     *

     * <p>If the current thread is {@linkplain java.lang.Thread#interrupt()

     * interrupted} by any thread before or while it is waiting, then an

     * {@code InterruptedException} is thrown.  This exception is not

     * thrown until the lock status of this object has been restored as

     * described above.

     *

     * <p>

     * Note that the {@code wait} method, as it places the current thread

     * into the wait set for this object, unlocks only this object; any

     * other objects on which the current thread may be synchronized remain

     * locked while the thread waits.

     * <p>

     * This method should only be called by a thread that is the owner

     * of this object's monitor. See the {@code notify} method for a

     * description of the ways in which a thread can become the owner of

     * a monitor.

     *

     * @param      timeout   the maximum time to wait in milliseconds.

     * @throws  IllegalArgumentException      if the value of timeout is

     *               negative.

     * @throws  IllegalMonitorStateException  if the current thread is not

     *               the owner of the object's monitor.

     * @throws  InterruptedException if any thread interrupted the

     *             current thread before or while the current thread

     *             was waiting for a notification.  The <i>interrupted

     *             status</i> of the current thread is cleared when

     *             this exception is thrown.

     * @see        java.lang.Object#notify()

     * @see        java.lang.Object#notifyAll()

     */

    public final native void wait(long timeout) throws InterruptedException;

    

    

    /**

     * Wakes up a single thread that is waiting on this object's

     * monitor. If any threads are waiting on this object, one of them

     * is chosen to be awakened. The choice is arbitrary and occurs at

     * the discretion of the implementation. A thread waits on an object's

     * monitor by calling one of the {@code wait} methods.

     * <p>

     * The awakened thread will not be able to proceed until the current

     * thread relinquishes the lock on this object. The awakened thread will

     * compete in the usual manner with any other threads that might be

     * actively competing to synchronize on this object; for example, the

     * awakened thread enjoys no reliable privilege or disadvantage in being

     * the next thread to lock this object.

     * <p>

     * This method should only be called by a thread that is the owner

     * of this object's monitor. A thread becomes the owner of the

     * object's monitor in one of three ways:

     * <ul>

     * <li>By executing a synchronized instance method of that object.

     * <li>By executing the body of a {@code synchronized} statement

     *     that synchronizes on the object.

     * <li>For objects of type {@code Class,} by executing a

     *     synchronized static method of that class.

     * </ul>

     * <p>

     * Only one thread at a time can own an object's monitor.

     *

     * @throws  IllegalMonitorStateException  if the current thread is not

     *               the owner of this object's monitor.

     * @see        java.lang.Object#notifyAll()

     * @see        java.lang.Object#wait()

     */

    public final native void notify();

    

    

    /**

     * Wakes up all threads that are waiting on this object's monitor. A

     * thread waits on an object's monitor by calling one of the

     * {@code wait} methods.

     * <p>

     * The awakened threads will not be able to proceed until the current

     * thread relinquishes the lock on this object. The awakened threads

     * will compete in the usual manner with any other threads that might

     * be actively competing to synchronize on this object; for example,

     * the awakened threads enjoy no reliable privilege or disadvantage in

     * being the next thread to lock this object.

     * <p>

     * This method should only be called by a thread that is the owner

     * of this object's monitor. See the {@code notify} method for a

     * description of the ways in which a thread can become the owner of

     * a monitor.

     *

     * @throws  IllegalMonitorStateException  if the current thread is not

     *               the owner of this object's monitor.

     * @see        java.lang.Object#notify()

     * @see        java.lang.Object#wait()

     */

    public final native void notifyAll();

}