现在的位置: 首页 > 综合 > 正文

public final void wait (long millis)的解释

2018年03月20日 ⁄ 综合 ⁄ 共 1917字 ⁄ 字号 评论关闭

public final void wait (long millis)
Since: API Level 1

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the specified timeout expires. This method can only be invoked by a thread which owns this object's monitor; see notify() on how a thread
can become the owner of a monitor.
导致调用者线程等待,直到另一个线程调用notify()或者notifyAll()方法,或者指定的等待时间到达。这个方法仅仅能被拥有这个对象监视器的线程调用;查看notify()方法可以获取一个线程怎样成为拥有者的监视器。

A waiting thread can be sent interrupt() to cause it to prematurely stop waiting, so wait should be called in a loop to check that the condition that has been waited for has been met before continuing.
一个等待的线程在调用interrupt()方法后过早的停止等待,因此等待函数wait应该被放到一个循环中进行调用,每次执行循环前检查wait的条件是否还满足。

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.
在线程等待中,它将放弃对象监听器的拥有权。当它被通知或者打断时,在它重新启动前,将重新获取到监视器。

Parameters
millis  the maximum time to wait in milliseconds.
Throws
IllegalArgumentException  if millis < 0.
IllegalMonitorStateException  if the thread calling this method is not the owner of this object's monitor.
InterruptedException  if another thread interrupts this thread while it is waiting.
See Also

    * notify()
    * notifyAll()
    * wait()
    * wait(long, int)
    * Thread
例如:
    Runnable mTask = new Runnable() {
        public void run() {
            // Normally we would do some work here...  for our sample, we will
            // just sleep for 30 seconds.
            long endTime = System.currentTimeMillis() + 15*1000;
            while (System.currentTimeMillis() < endTime) {
                synchronized (mBinder) {
                    try {
                        mBinder.wait(endTime - System.currentTimeMillis());
                    } catch (Exception e) {
                    }
                }
            }

            // Done with our work...  stop the service!
            AlarmService_Service.this.stopSelf();
        }
    };
线程会阻塞到mBinder.wait(endTime - System.currentTimeMillis());位置,直到endTime等于System.currentTimeMillis(),线程才能继续执行。
外层使用一个 while (System.currentTimeMillis() < endTime)循环保证线程不会退出。

抱歉!评论已关闭.