close

●Thread.sleep(4000)表執行緒會暫時停止執行4秒後,系統會再將之排程預備執行,因此並不保證一定在4秒後開始執行。

●根據硬體/作業系統/當時系統負載的不同,sleep在不同情況之下是不一定準確。

public class VolatileThread implements Runnable {
    public volatile boolean stop;       //會並行

    @Override
    public void run() {
        while(!stop){
            
        }
        System.out.println("執行緒結束:" + (System.currentTimeMillis()));
    }
}

 

public class Test0610 {
    public static void main(String[] args) {     
        VolatileThread vt = new VolatileThread();
        Thread t = new Thread(vt);
        t.start();
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        vt.stop = true;
        System.out.println("送出停止訊號:" + System.currentTimeMillis());
        System.out.println("主程式結束");
    }
}
 

volatile 參考資料:http://www.test104.com/tw/tech/9223.html

 

arrow
arrow
    創作者介紹
    創作者 淺翔 的頭像
    淺翔

    翔の學習淺談

    淺翔 發表在 痞客邦 留言(0) 人氣()