public final void wait (long millis)的解释

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)循环保证线程不会退出。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值