在拿到一个项目或者需求之后,都会根据需求来先把架构设计完好,设计架构是有时会遇到多个线程的问题,自然就会遇到线程没有杀除成功的问题,
若是采用一个volatile 类型的thread,然后在杀除她的时候,将正在run的thread传给一个临时变量,将临时变量赋予null.
public class SocketThread extends Thread{
private volatile Thread runner;
private Socket socket;
public SocketThread(){
}
public SocketThread(Socket socket){
this.socket = socket;
this.runner = null;
}
public synchronized void startChecking(){
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public synchronized void stopChecking(){
if(runner != null){
Thread moribund = runner;
if (socket != null && socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// do nothing
}
}
socket = null;
runner = null;
moribund.interrupt();
}
}
public void run(){
while (Thread.currentThread() == runner) {
// do something
}
}
}
这样的话可以解决thread的杀除问题,如有异意,请提出.