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