Java如何停止線程?

在Java編程中,如何停止線程?

以下示例演示了如何通過創建一個用戶定義的方法run()方法和Timer類來停止線程。

package com.zaixian;

import java.util.Timer;
import java.util.TimerTask;

class CanStop extends Thread {
    private volatile boolean stop = false;
    private int counter = 0;

    public void run() {
        while (!stop && counter < 10000) {
            //System.out.println(counter++);
        }
        if (stop){
            System.out.println("Detected stop");
        }
    }

    public void requestStop() {
        stop = true;
    }
}

public class StoppingThread {
    public static void main(String[] args) {
        final CanStop stoppable = new CanStop();
        stoppable.start();

        new Timer(true).schedule(new TimerTask() {
            public void run() {
                System.out.println("Requesting stop");
                stoppable.requestStop();
            }
        }, 350);
    }
}

上述代碼示例將產生以下結果 -

Requesting stop
Detected stop

上一篇: Java線程 下一篇: Java簡單GUI實例