在拿到一個項目或者需求之後,都會根據需求來先把架構設計完好,設計架構是有時會遇到多個線程的問題,自然就會遇到線程沒有殺除成功的問題,
若是採用一個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的殺除問題,如有異意,請提出.