美文网首页
Concurrency: Object中线程相关方法javado

Concurrency: Object中线程相关方法javado

作者: CalmHeart | 来源:发表于2019-06-23 10:15 被阅读0次
    • Object中wait 和notify都是native方法 因为这些方法都是线程相关的 与操作系统的交互比较紧密 只不过JVM对操作系统底层的线程方法做了一层抽象 是介于操作系统和开发者中间的桥梁。

    方法签名
    java.lang.Object public final void wait()
    throws InterruptedException

    导致一个线程等待直到另外一个线程调用了这个对象的notify()或者notifyAll()方法 换言之,wait()方法的行为同简单的调用wait(0)一样。
    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).

    reference method body

     public final void wait() throws InterruptedException {
            wait(0);
        }
    

    当前的线程必须拥有对象的监视器(Call it 锁),这个线程释放锁的拥有权直到另外一个线程通过调用notify或者notifyAll方法去唤醒在等待这个对象锁的线程,一个线程等待直到可以重新获取锁的拥有权并继续执行
    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.

    在一个参数的版本中,中断及假的唤醒是有可能的这个方法必须在一个循环中
    As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

               synchronized (obj) {
                   while (<condition does not hold>)
                       obj.wait();
                   ... // Perform action appropriate to condition
               }
    

    这个方法应该被一个拥有对象锁所有权的线程调用,参看notify方法的描述的几种获取对象锁的几种方式
    This method should only be called by a thread that is the owner of this object's monitor. See the 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 the object's monitor.
    InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
    See Also:
    notify(), notifyAll()


    方法签名
    java.lang.Object public final void wait(long timeout)
    throws InterruptedException

    导致当前的线程等待直到被其他拥有对象锁的线程调用notify或者notifyAll方法 或者一个指定的时间已经流逝 当前的线程必须对象的锁
    Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
    The current thread must own this object's monitor.

    这个方法将导致当前的线程T被放到这个对象的等待集合中,放弃了对于这个对象所有的同步声明,当前的线程将被线程调度禁用并且一直处于休眠状态知道以下4种情况之一发生:
    This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:
    另外一个线程调用了这个对象的notify方法并且当前的线程碰巧被选中称为被唤醒的线程
    Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
    其他的线程调用了这个对象的notifyAll方法
    Some other thread invokes the notifyAll method for this object.
    其他的线程中断了当前线程
    Some other thread interrupts thread T.
    指定的实际时间或多或少已经流逝,如果timeout param是0 则会忽略实际时间直到被唤醒
    当前的线程将会从等待集合中移除,并重新获取线程的调度,将和其他的线程拥有同等的权利去竞争对象的同步权,一旦获取了对象的控制权 对对象的同步声明将恢复到调用前的状态,即到调用wait方法时的情况,因此,从wait方法返回时,当前的线程T的同步状态与调用wait方法时的同步状态完全相同
    The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.
    The thread T 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 wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

    一个线程也可以被唤醒并非通过notify、interrupted、timeout 被称为伪唤醒 即使这种情况在实际的场景中很少出现,应用必须通过测试这种情况发生的条件来避免它们 如果这个条件不满足继续等待 换言之,wait method 应该总是在一个循环中。
    A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. 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:

               synchronized (obj) {
                   while (<condition does not hold>)
                       obj.wait(timeout);
                   ... // Perform action appropriate to condition
               }
    

    关于这个主题的更多内容 参看Doug Lea的并发编程指南的3.2.3章节或者是Joshua Bloch的Effective Java 50条目 如果当前的线程在调用while之前或中间被其他的线程中断 一个中断异常将会抛出 这个异常将不会抛出直到这个对象锁的状态像上面提到的那样被恢复。
    (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).
    If the current thread is interrupted by any thread before or while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.
    注意wait方法 因为它将当前的线程放到这个对象的等待集合中,不释放这个对象,当前的线程可能被同步的其他对象在线程等待时仍然被锁定 这里需要注意死锁的情况发生Deadlock

    Wiki:
    在并发的计算中 死锁是指组中的每个成员都在等待包括自己在内的其他成员采取行动的状态 比如发送一个消息或者更为常见的释放一个锁 死锁在一个多处理系统 并行计算或者分布式系统 软件和硬件锁用于仲裁共享资源和实现进程同步
    In concurrent computing, a deadlock is a state in which each member of a group is waiting for another member, including itself, to take action, such as sending a message or more commonly releasing a lock.[1] Deadlock is a common problem in multiprocessing systems, parallel computing, and distributed systems, where software and hardware locks are used to arbitrate shared resources and implement process synchronization.[2]

    在一个操作系统中,死锁可能发生在一个进程或线程因为请求另外一个等待进程正在持有的系统资源而进入等待状态,依次等待对方进程持有的资源 如果进程无法无限期地更改其状态,因为它所请求的资源正在被另一个等待的进程使用,则系统被称为处于死锁中

    In an operating system, a deadlock occurs when a process or thread enters a waiting state because a requested system resource is held by another waiting process, which in turn is waiting for another resource held by another waiting process. If a process is unable to change its state indefinitely because the resources requested by it are being used by another waiting process, then the system is said to be in a deadlock.[3]

    在一个通信系统中,死锁将会由于丢失或者是损失信号量而产生并非因为资源的竞争
    In a communications system, deadlocks occur mainly due to lost or corrupt signals rather than resource contention.[4]

    Note that the 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.

    这个方法应该被一个拥有对象锁所有权的线程调用,参看notify方法的描述的几种获取对象锁的几种方式
    This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

    Params:
    timeout – the maximum time to wait in milliseconds.
    Throws:
    IllegalArgumentException – if the value of timeout is negative.
    IllegalMonitorStateException – if the current thread is not the owner of the object's monitor.
    InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
    See Also:
    notify(), notifyAll()


    方法签名
    java.lang.Object public final void wait(long timeout,
    int nanos)
    throws InterruptedException

    Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
    这个方法类似于只带一个参数的wait方法,但是它允许更好的控制在放弃前等待通知的时间
    This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The amount of real time, measured in nanoseconds, is given by:
    1000000*timeout+nanos
    In all other respects, this method does the same thing as the method wait(long) of one argument. In particular, wait(0, 0) means the same thing as wait(0).

    当前的线程必须拥有对象的锁,这个线程释放对象的锁并且等待直到下面的两种情况发生:
    The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

    1. 另一个线程通过调用notify或者notifyAll方法唤醒了等待这个对象的线程(及其他的小伙伴)
      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.

    2. 超时时间(由超时毫秒加上nanos nanosecseconds参数指定)已经过去
      The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.

    线程等待,直到它可以重新获得监视器的所有权,并继续执行
    The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

    As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

               synchronized (obj) {
                   while (<condition does not hold>)
                       obj.wait(timeout, nanos);
                   ... // Perform action appropriate to condition
               }
    

    This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

    Params:
    timeout – the maximum time to wait in milliseconds.
    nanos – additional time, in nanoseconds range 0-999999.
    Throws:
    IllegalArgumentException – if the value of timeout is negative or the value of nanos is not in the range 0-999999.
    IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.
    InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.


    方法签名

    • java.lang.Object public final void notify()

    唤醒单个在等待这个对象锁的线程,如果存在多个线程在等待这个对象,那么选择其中的一个去唤醒,这个是任意的,由实现决定,一个线程通过调用wait()方法等待对象的锁。
    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 wait methods.

    这个被唤醒的线程将不能继续运行直到当前的线程释放了这个对象的监事权(锁),被唤醒的线程将同其他正在活跃的线程同等地去竞争对于这个对象的同步权利,例如: 这个被唤醒的线程与其他的线程在下一次锁定这个对象上拥有同等的权利。
    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.

    这个方法只能被拥有这个对象锁的线程调用,一个线程拥有三种方式成为锁的拥有者:

    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:
    通过执行这个对象的一个同步实例方法synchronized method
    By executing a synchronized instance method of that object.
    通过执行这个对象的同步代码片段 synchronized statement
    By executing the body of a synchronized statement that synchronizes on the object.
    对于Class类型的对象,通过执行这个类的static method
    For objects of type Class, by executing a synchronized static method of that class.

    同一时刻只有一个线程拥有对象的锁
    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 Also:
    notifyAll(), wait()


    方法签名
    java.lang.Object public final void notifyAll()

    唤醒所有在等待这个对象锁的线程,可以通过调用对象的wait()方法来等待对象的锁
    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 wait methods.

    这个被唤醒的线程将不能继续运行直到当前的线程释放了这个对象的监事权(锁),被唤醒的线程将同其他正在活跃的线程同等地去竞争对于这个对象的同步权利,例如: 这个被唤醒的线程与其他的线程在下一次锁定这个对象上拥有同等的权利。
    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.

    这个方法应该被另一个拥有对象锁的线程调用 参看notify方法了解一个线程获取对象锁的的3种方式的描述。

    object instance synchronized method
    synchronized statement
    static synchronized method

    This method should only be called by a thread that is the owner of this object's monitor. See the 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 Also:
    notify(), wait()


    相关文章

      网友评论

          本文标题:Concurrency: Object中线程相关方法javado

          本文链接:https://www.haomeiwen.com/subject/yempzqtx.html