各种方法来阻止一个线程 - 这是正确的方法

Che*_*eng 4 java multithreading

我遇到了阻止线程的不同建议.我可以知道,这是正确的方法吗?还是取决于?

使用线程变量 http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

private volatile Thread blinker;

public void stop() {
    blinker = null;
}

public void run() {
    Thread thisThread = Thread.currentThread();
    while (blinker == thisThread) {
        try {
            thisThread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}
Run Code Online (Sandbox Code Playgroud)

使用布尔标志

private volatile boolean flag;

public void stop() {
    flag = false;
}

public void run() {
    while (flag) {
        try {
            thisThread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}
Run Code Online (Sandbox Code Playgroud)

将线程变量与中断一起使用

private volatile Thread blinker;

public void stop() {
    blinker.interrupt();
    blinker = null;
}

public void run() {
    Thread thisThread = Thread.currentThread();
    while (!thisThread.isInterrupted() && blinker == thisThread) {
        try {
            thisThread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}
Run Code Online (Sandbox Code Playgroud)

ska*_*man 6

这些都不是"正确的"方式,它们都是有效的.您使用哪一个取决于您的具体情况,哪一个最适合您.

只要你不使用Thread.stop(),并且整理你的线程(连接,临时文件等)留下的任何资源,那么你如何去做它并不重要.