1. 程式人生 > >55、執行緒睡眠

55、執行緒睡眠

執行緒睡眠

Thread中的sleep方法可以使當前執行緒睡眠,執行緒睡眠後,裡面的任務不會執行,待睡眠時間過後會自動甦醒,從而繼續執行任務。

Thread中有兩個過載的sleep方法
sleep(long millis),指定睡眠毫秒數
sleep(long millis, int nanos),第一個引數是毫秒,第二個引數是納秒

程式碼示例:

package com.sutaoyu.Thread;

public class test_7 {
    public static void main(String[] args){
        new Thread() {
            
public void run() { for(int i = 0;i < 10;i++) { try { Thread.sleep(1000); }catch(InterruptedException e) { e.printStackTrace(); } System.out.println("monkey"); } } }.start();
new Thread() { public void run() { for(int i = 0;i < 10;i++) { try { Thread.sleep(1000); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(
"1024"); } } }.start(); } }