且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:如何中断/停止线程?

更新时间:2022-06-08 22:21:44

你真的没有理由需要使用 volatile 标志。相反,只需使用 isInterrupted() 。另外,为什么要在另一个线程对象中包装 Scan 线程对象?这对我来说似乎完全没必要。

There's really no reason you need to use a volatile flag. Instead, just query the thread for its state with isInterrupted(). Also, why are you wrapping your Scan thread object in another thread object? That seems completely unnecessary to me.

这里'你应该做什么

public class Middleware {
    private Scan scan;

    public void read() {
        try {
            // do stuff

            scan = new Scan();
            scan.start();
        } catch (UnknownHostException ex) {
            // handle exception
        } catch (IOException ex) {
            // handle exception
        }
    }

    private class Scan extends Thread {

        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    // my code goes here
                } catch (IOException ex) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    public void stop() {
        if(scan != null){
            scan.interrupt();
        }
    }
}

这是一个example 。另外,我不建议扩展 Thread

Here's an example. Also, I wouldn't recommend extending Thread.