线程:sleep()、wait()、yield()和join()方法

        1.sleep()和wait()
        这两个方法都可以让调用它的线程沉睡(sleep)/停止运行(wait)指定的时间,到了这个时间,线程就会自动醒来,变为可运行状态(RUNNABLE)。

        public static native void sleep(long millis) throws InterruptedException;  
        public static void sleep(long millis, int nanos) throws InterruptedException

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

        Parameters:
        millis - the length of time to sleep in milliseconds.毫秒数
        nanos - 0-999999 additional nanoseconds to sleep.纳秒数

        调用sleep()方法并不会让线程释放它所持有的同步锁;而且在这期间它也不会阻碍其它线程的运行。
        当调用了某个对象的wait()方法时,当前运行的线程就会转入WAITING状态,等待别的线程再次调用这个对象的notify()或者notifyAll()方法唤醒它,或者到了指定的最大等待时间,线程自动醒来。如果线程调用了某个对象的wait()方法,这个线程就会释放这个对象所持有的同步资源(不会释放其他对象的同步锁)。jdk api doc: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
  1. package edu.hust.test;
  2. public class ThreadSleep implements Runnable {
  3.     /*
  4.      * 让线程睡眠的理由很多,比如(1)认为该线程运行得太快,需要减缓一下,以便和其他线程协调;(2)查询当时的股票价格,每睡5分钟查询一次,可以节省带宽,而且即时性要求也不那么高。
  5.      * 注意:时间的精确性。线程醒来之后不会马上运行,而要等待cpu给其分配时间片。因此sleep()中指定的时间并不是线程不运行的精确时间!所以不能依赖sleep()方法提供十分精确的定时。
  6.      * 我们可以看到很多应用程序用sleep()作为定时器,实际是不精确的。
  7.      * 
  8.      * 
  9.      * Thread.sleep(5 * 1000)和Thread.currentThread().sleep(5 * 1000)没区别:都表示让当前线程sleep 5秒.
  10.      * 一个是通过类获取静态方法,一个是通过实例对象获得静态方法(sleep()为静态方法).
  11.      * 
  12.      * 注意:sleep并不是Thread的一个STATE
  13.      */
  14.     public void execute() {
  15.         synchronized(this) {
  16.             try {
  17.                 System.out.println(Thread.currentThread().getName() + ", sleep()前");
  18.                 Thread.sleep(1000);
  19.                 System.out.println(Thread.currentThread().getName() + ", sleep()后");
  20.             } catch (InterruptedException e) {
  21.                 System.out.println(Thread.currentThread().getName() + ", 谁把我吵醒了.....");
  22.             }
  23.             //此处如果使用System.err, 会有很意外的结果。System.out和System.err的区别请见blog
  24.             System.out.println(Thread.currentThread().getName() + ", run()结束..进入TERMINATED状态");
  25.         }
  26.     }
  27.     
  28.  
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值