1
我目前工作的一個Java的網絡圖書館,我面臨着DatagramSocket的一個問題。我有一個線程持續監聽UDP請求,並且每當我停止並關閉其關聯的DatagramSocket時,都會有一個線程不會停止。停止一個DatagramSocket線程
這裏是重現該問題的代碼示例:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class UDPListener implements Runnable {
private volatile boolean isRunning;
private volatile boolean clientClosed;
private int port;
private DatagramSocket client;
public UDPListener(int listeningPort) {
this.port = listeningPort;
}
public void open() throws SocketException {
this.clientClosed = false;
if (this.client != null) {
this.client.close();
}
this.client = new DatagramSocket(this.port);
}
@Override
public void run() {
this.isRunning = true;
this.clientClosed = false;
DatagramPacket packet = new DatagramPacket(new byte[256], 256);
while (this.isRunning) {
try {
this.client.receive(packet);
} catch (SocketException e) {
if (!this.clientClosed) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
this.client.disconnect();
System.out.println("stopped");
}
public void stop() {
this.isRunning = false;
this.clientClosed = true;
this.client.close();
}
public static void main(String[] args) throws InterruptedException, SocketException {
UDPListener t = new UDPListener(0);
ExecutorService e = Executors.newFixedThreadPool(1);
t.open();
e.submit(t);
Thread.sleep(1000);
t.stop();
}
}
我與選擇類同樣的問題。
我做錯了嗎?
看來我是不是我的問題:(清除線程開始與執行停止(」停止「),但有一些線程我沒有明確啓動,繼續在後臺運行,留下使用的端口並阻止應用程序退出 – Maliafo