更新時間:2022-12-09 11:21:12 來源:動力節點 瀏覽4402次
與任何其他編程語言一樣,Java 支持延遲。要理解延遲的概念,我們需要了解Java線程,了解線程后,您肯定會了解 main Thread,即調用 main 函數的線程。所以現在如果我們想使用延遲,唯一可能的方法就是暫停線程的執行。Java 的 API 為這個功能提供了方法。
顧名思義,sleep 方法是一種在 Java 中執行延遲的快速但骯臟的方法。此方法存在于 Thread 類中。它只是指示當前線程休眠一段特定時間。
句法:
Thread.Sleep(<Time In Miliseconds>)
sleep 方法以毫秒為單位接受輸入。所以,如果你想暫停執行 5 秒,你需要在 sleep 方法中傳遞 5000。在睡眠方法的情況下,該過程顯示為正在進行的工作,而操作設置為暫停。現在,在這種情況下,如果處理器需要處理其他一些高優先級進程,則 sleep 方法的執行可能會被中斷。因此,為此目的,Java 的 API 實現了 sleep 方法以拋出 InterruptedException。
下面是Thread類的sleep方法的實現。
public static void sleep(long ms) throws InterruptedException
{
sleep(ms, 0);
}
因此,每當我們調用 sleep 方法時,我們都需要轉發異常或使用 try & catch 塊處理異常,如下面的代碼所示:
try {
Thread.sleep(timeInSeconds * 1000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
執行或調用睡眠方法的另一種方法是使用 TimeUnit 的睡眠方法。在內部它也使用 Thread 的 sleep 方法,但它的不同之處在于它接受 Unit Time 并且可以在參數中傳遞相同的方法,如下所示:
句法:
TimeUnit.SECONDS.sleep(<timeInSeconds>);
例子:
// TimeUnit's sleep() method
import java.util.concurrent.*;
class TimeUnitMain{
public static void main(String args[]) {
long time = 0;
//TimeUnit Object to call the sleep method
TimeUnit time = TimeUnit.SECONDS;
try {
// Calling the sleep method on the object of TimeUnit Class
time.sleep(time);
} catch (InterruptedException e) {
System.out.println("Interrupted Exception Caught"+ e);
}
}
}
我們可以使用 wait 方法在多線程環境和同步塊內暫停執行。
像 wait() 一樣,我們有一個方法 notify() 和 notifyAll(),這些方法在 wait() 方法之后被調用。我們需要確保我們只從同步塊調用 wait() 方法。
讓我們看一個簡單的例子,在下面的例子中,我們使用線程計算前 100 個數字的總和,并在不同的線程中打印總和。
所以,下面是我們的 ThreadOne 類:
package delay.example;
public class ThreadOne extends Thread{
int sum;
@Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
sum += i;
}
notify();
}
}
}
下面是創建 ThreadOne 對象并計算總和的主類:
package delay.example;
public class ThreadMain {
public static void main(String[] args){
ThreadOne t1 = new ThreadOne();
t1.start();
System.out.println("Value of the ThreadOne's num is: " + t1.sum);
}
}
上述代碼的輸出如下所示:
ThreadOne 的 num 值為:0
或者
ThreadOne 的 num 值是:10或其他值,具體取決于將變量 sum 發送到控制臺進行打印時的值。
我們使用相同的 ThreadOne 類:
package delay.example;
public class ThreadOne extends Thread{
int sum;
@Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
sum += i;
}
notify();
}
}
}
但是修改 ThreadMain 類如下:
package delay.example;
public class ThreadMain {
public static void main(String[] args){
ThreadOne t1 = new ThreadOne();
t1.start();
synchronized(t1){
try{
System.out.println("Waiting For the Thread t1 to complete its execution: ");
t1.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Value of the ThreadOne's num is: " + t1.sum);
}
}
}
輸出:
等待線程 t1 完成執行:
ThreadOne 的 num 值為:4950
這是由于 wait() 暫停了 main() 線程,直到 t1 線程執行它的方法并調用了 notify() 方法。如果大家想了解更多相關知識,不妨來關注一下本站的Java視頻教程,里面的課程內容細致全面,通俗易懂,很適合沒有基礎的小伙伴學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習