[转]Java 关闭线程的安全方法
http://www.blogjava.net/Green-nut/articles/335149.html
Java 之前有个api函数可以直接关闭线程, stop(), 后来, 取消了. 其替代的方式主要有两种:
private boolean _run = true;
public void stopThread(boolean run) {
this._run = !run;
}
@Override
public void run() {
while(_run) {
///
//数据处理
///
}
//super.run();
}
public static void main(String[] args) {
StopThread thread = new StopThread();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//停止线程
thread.stopThread(true);
}
}
@Override
try {
System.out.println(“start“);
while(!this.isInterrupted()) {
///
//数据处理
///
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(“stop“);
//super.run();
}
public static void main(String[] args) {
StopThread thread = new StopThread();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
System.out.println(“interrupt“);
}
}