您的位置 首页 java

并发编程(七)java中的sleep方法 wait方法

今天讲java并发中的几个方法,主要回答这些问题:1.是否释放锁?2.是否对中断敏感 ?3.是否释放CPU?

1.sleep方法

我们先来看源码

 public static native  void  sleep(long millis) throws Interrupted Exception ;
复制代码  

可以看大是个native方法, 其中还有段英文解释,我直接贴原文:

 Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds plus the specified
number of nanoseconds, subject to the precision and accuracy of system
timers and schedulers. The thread does not lose ownership of any
monitors.
复制代码  

大致意思是:使当前正在执行的线程休眠(暂时停止执行)指定的毫秒数加上指定的纳秒数,这取决于系统计时器和调度程序的精度和准确性。线程不会失去任何监视器的所有权。

所以可以得到sleep方法不释放锁

throws InterruptedException下有一段解释

 if any thread has interrupted the current thread. The <i>interrupted status</i> of the current thread is cleared when this exception is thrown.
复制代码  

表示如果如果抛出InterruptedException异常会打断当前线程

是否释放CPU有一个代码例子:

 public class SleepRelaseCPU {
    public static void main(String[] args) {

        for(int i = 0; i < 100; i++) {
            Thread thread = new Thread(new SubThread(),"Daemon Thread!"+i);
            thread.start();
        }
    }
    static class SubThread implements Runnable {
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName());
                Thread.sleep(500000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("FINISH!");
            }
        }
    }
}
复制代码  

当运行这段代码时,我分别执行了三次,可以观察cpu利用率明显升高三次后又降下来,但是程序还没有结束,所以 sleep方法是释放CPU

2.wait方法

我们先来看源码

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



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

复制代码  

这个wait方法还是一个native方法,我们可以看下面的英文解释:

 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 {@code notify} method or the {@code notifyAll} method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
复制代码  

意思是当前线程拥有线程的monitor锁,如果调用wait方法会释放这个锁一直等到其他线程唤醒这个线程。

所以说明wait方法释放锁

而且这个wait方法throws InterruptedException所以对中断敏感

而且wait是让出cpu时间片,进入等待队列

文章来源:智云一二三科技

文章标题:并发编程(七)java中的sleep方法 wait方法

文章地址:https://www.zhihuclub.com/194011.shtml

关于作者: 智云科技

热门文章

网站地图