Java通過在主迴圈中判斷Boolean來停止執行緒

FrankYou發表於2017-03-08

 Java程式碼:

package Threads;

/**
 * Created by Frank
 */
public class StopBoolean extends Thread {

    // 確保變化對其它執行緒可見(主要是主執行緒要可見)
    protected volatile boolean done = false;

    public void run() {
        while (!done) {
            System.out.println("StopBoolean running");
            try {
                sleep(720);
            } catch (InterruptedException e) {
                return;
            }
        }
        System.out.println("StopBoolean finished");
    }

    public void shutDown() {
        done = true;
    }

    public static void main(String[] args) throws InterruptedException {
        StopBoolean t1 = new StopBoolean();
        t1.start();
        Thread.sleep(1000 * 5);
        t1.shutDown();
    }
}

 

相關文章