如何在Java中中断停止线程?

如何在Java中中断停止线程?,第1张

如何在Java中中断/停止线程

确实没有必要使用

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

这是你应该做的

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 pre goes here     } catch (IOException ex) {         Thread.currentThread().interrupt();     } }        }    }    public void stop() {        if(scan != null){ scan.interrupt();        }    }}

这是一个例子。另外,我不建议扩展

Thread

通常,线程在被中断时终止。那么,为什么不使用本地布尔值呢?试试isInterrupted():

   Thread t = new Thread(new Runnable(){        @Override        public void run() { while(!Thread.currentThread().isInterrupted()){     // do stuff          }}});    t.start();    // Sleep a second, and then interrupt    try {        Thread.sleep(1000);    } catch (InterruptedException e) {}    t.interrupt();


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5438830.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-11
下一篇2022-12-11

发表评论

登录后才能评论

评论列表(0条)

    保存