TimeUnit類的sleep()方法用於使用此時間單位執行Thread.sleep。這是一種方便的方法,可以將時間參數睡眠為Thread.sleep方法所需的形式。
用法:
public void sleep(long timeout) throws InterruptedException
參數:此方法接受強製參數超時,這是最短的睡眠時間。如果小於或等於零,則根本不睡覺。
返回值:此方法不返回任何內容。
異常:如果在睡眠期間被中斷,則此方法將引發InterruptedException。
以下示例程序旨在說明TimeUnit sleep()方法的實現:
示例1:
// Java program to demonstrate
// sleep() method of TimeUnit Class
import java.util.concurrent.*;
class GFG {
public static void main(String args[])
{
// Get time to sleep
long timeToSleep = 0L;
// Create a TimeUnit object
TimeUnit time = TimeUnit.SECONDS;
try {
System.out.println("Going to sleep for "
+ timeToSleep
+ " seconds");
// using sleep() method
time.sleep(timeToSleep);
System.out.println("Slept for "
+ timeToSleep
+ " seconds");
}
catch (InterruptedException e) {
System.out.println("Interrupted "
+ "while Sleeping");
}
}
}
輸出:
Going to sleep for 0 seconds Slept for 0 seconds
示例2:
// Java program to demonstrate
// sleep() method of TimeUnit Class
import java.util.concurrent.*;
class GFG {
public static void main(String args[])
{
// Get time to sleep
long timeToSleep = 10L;
// Create a TimeUnit object
TimeUnit time = TimeUnit.SECONDS;
try {
System.out.println("Going to sleep for "
+ timeToSleep
+ " seconds");
// using sleep() method
time.sleep(timeToSleep);
System.out.println("Slept for "
+ timeToSleep
+ " seconds");
}
catch (InterruptedException e) {
System.out.println("Interrupted "
+ "while Sleeping");
}
}
}
輸出:
Going to sleep for 10 seconds Slept for 10 seconds
相關用法
- Java TimeUnit values()用法及代碼示例
- Java TimeUnit toMillis()用法及代碼示例
- Java TimeUnit toDays()用法及代碼示例
- Java TimeUnit valueOf()用法及代碼示例
- Java TimeUnit toMinutes()用法及代碼示例
- Java TimeUnit convert()用法及代碼示例
- Java TimeUnit toSeconds()用法及代碼示例
- Java TimeUnit toNanos()用法及代碼示例
- Java TimeUnit toHours()用法及代碼示例
- Java TimeUnit toMicros()用法及代碼示例
- Java Java.util.Collections.disjoint()用法及代碼示例
- Java Java lang.Long.byteValue()用法及代碼示例
注:本文由純淨天空篩選整理自RishabhPrabhu大神的英文原創作品 TimeUnit sleep() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。