确实没有必要使用
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();


