# 凍結執行緒 sleep()

在 [認識多執行緒](/java-15/java-15-1.md) 中的範例，故意加了一個拖慢執行緒的迴圈；\
那透過讓執行緒小睡片刻，如此便可稍緩執行緒的執行。

```
for(int i=0;i<3;i++)
{
    for(int j=0;j<100000000;j++);
    System.out.println(name);
}
```

我們可以在迴圈內加個 sleep()，在［Java］執行緒生命週期（介紹）附註中提到：

> sleep() 函數，可用來設定睡眠時間，即 sleep(long millis)。\
> 毫秒（千分之一秒）。

例如 sleep(1000) 就代表睡1秒鐘(1秒後就會醒來)。

因此將迴圈改成：

```
for(int i=0;i<3;i++)
      {
         try
         {
            sleep((int)(1000*Math.random()));
         }
         catch(InterruptedException e){}
         System.out.println(name);
      }
```

sleep() 可能會拋出 InterruptedException  例外，所以我們將 sleep() 撰寫在 try-catch 區塊內。

而 sleep() 的引數 (int)(1000\*Math.random()) 部分：\
我們透過 Math.random() 來產生 0～1的浮點數亂數，乘上1000 即 0\~1000 之間的浮點數亂數；\
最後在前面強制轉型成整數，所以加上(int)。

## 完整的程式碼

```
class multi_Test
{
   private String name;
   public multi_Test(String str)
   {
      name=str;
   }
   public void show()
   {
      for(int i=0;i<3;i++)
      {
         try
         {
            sleep((int)(1000*Math.random()));
         }
         catch(InterruptedException e){}
         System.out.println(name);
      }
   }
}

public class multi_thread_3
{
   public static void main(String args[])
   {
      multi_Test apple=new multi_Test("apple");
      multi_Test pen=new multi_Test("pen");
      apple.start();
      pen.start();
   }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://java.4-x.tw/java-15/java-15-sleep.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
