Java关闭线程的安全方法
Java 之前有个api函数可以直接关闭线程, stop(), 后来, 取消了. 其替代的方式主要有两种:
1. 自己加入一个成员变量, 我们在程序的循环里面, 轮流的去检查这个变量, 变量变化时,就会退出这个线程. 代码示例如下
package com.test;public class StopThread extends Thread { 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); } }package com.test;public class StopThread extends Thread { @Override public void run() { 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"); } }