執行緒sleep方法的使用(原始碼解讀)

2021-09-07 09:06:36 字數 2209 閱讀 3269

package com.thread;

public class testsleep

}class sleepthread implements runnable

try catch (interruptedexception e) }

}

sleep方法原始碼如下:

/**

* causes the currently executing thread to sleep (temporarily cease

* execution) for the specified number of milliseconds, subject to

* the precision and accuracy of system timers and schedulers. the thread

* does not lose ownership of any monitors.

** @param millis

* the length of time to sleep in milliseconds

** @throws illegalargumentexception

* if the value of is negative

** @throws interruptedexception

* if any thread has interrupted the current thread. the

* interrupted status of the current thread is

* cleared when this exception is thrown.

*/public static native void sleep(long millis) throws interruptedexception;

/*** 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.

** @param millis

* the length of time to sleep in milliseconds

** @param nanos

* additional nanoseconds to sleep

** @throws illegalargumentexception

* if the value of is negative, or the value of

* is not in the range

** @throws interruptedexception

* if any thread has interrupted the current thread. the

* interrupted status of the current thread is

* cleared when this exception is thrown.

*/public static void sleep(long millis, int nanos)

throws interruptedexception

if (nanos < 0 || nanos > 999999)

if (nanos >= 500000 || (nanos != 0 && millis == 0))

sleep(millis);

}

解讀原始碼:

這段**上面的注釋意思如下:

sleep(millis)方法用於讓當前執行緒暫停執行指定的毫秒數,取決於系統時間的精確度,當前執行緒並不會失去鎖。

sleep方法是乙個靜態方法。

sleep方法的使用,進入sleep狀態不釋放鎖

thread類中的靜態方法sleep 當乙個執行中的執行緒呼叫了thread的sleep 方法後,呼叫執行緒會暫時讓出時間的執行權,這期間不參與cpu的排程,但是該執行緒持有的鎖是不讓出的。時間到了會正常返回,執行緒處於就緒狀態,然後參與cpu排程,獲取到cpu資源之後就可以執行。如果在睡眠期間,其...

mysql 執行緒池原始碼 執行緒池原始碼解析

1.前言 我個人覺得理論性的東西可能大家都懂,但是具體的實現細節可能並不是很清楚所以才想記錄一下,加深記憶。2.關鍵原始碼解析 1 ctl private final atomicinteger ctl new atomicinteger ctlof running,0 private static...

執行緒sleep方法的面試題

執行緒sleep方法的面試題 thread類原始碼展示sleep方法 問題 下面 中的t.sleep 3000 會讓自定義的t執行緒睡眠3秒鐘嗎?如果不會,那麼是讓主線程睡眠3秒嗎?為什莫呢?class mythread extends thread public class sleeptest c...