我的代码中有一个没完没了的线程。这个线程创建udp read方法并无休止地监听连接。我想做的是在手动停止线程执行后执行一段代码(通过在eclipse中单击stop按钮)。他们是否有可能做到这一点?在搜索相同的方法时,我遇到了一个ondestroy()方法,但遗憾的是,它只适用于android java!!!
wlwcrazw1#
首先,停止网络读取线程的正确方法是关闭套接字。然后read/receive方法抛出一个异常并捕获它
private final DatagramSocket udpSocket; private volatile boolean closed; // or AtomicBoolean ... public synchronized void start() throws IOException { if (closed) { throw new IOException("Closed"); } new Thread(new Runnable() { @Override public void run() { final byte[] buffer = new byte[1024]; final DatagramPacket dp = new DatagramPacket(buffer, buffer.length); Throwable error = null; try { while(true) { udpSocket.receive(dp); final String message = new String(buffer, 0, dp.getLength()); System.out.println(message); } } catch (Throwable t) { if (!closed) { error = t; } } if (error != null) { // do some work for error } } }).start(); } public void close() throws IOException { synchronized(this) { if (closed) return; closed = true; } udpSocket.close(); }
当您在ide中单击stop按钮时,通常会立即(异常地)/终止jvm进程。我建议您在console中运行您的进程,并使用ctrl+c停止该进程并添加一个shutdownhook:
public static void main(String[] args) { Runtime.getRuntime().addShutdownHook( new Thread( new Runnable() { @Override public void run() { System.out.println("Shutdown"); } })); }
或者在eclipse中运行它,但在windows上停止taskkill,在linux上从命令行界面停止kill,以正常关闭jvm进程。详见http://www.oracle.com/technetwork/java/javase/signals-139944.htmlhttps://docs.oracle.com/javase/7/docs/api/java/lang/runtime.html#addshutdownhook%28java.lang.thread%29
1条答案
按热度按时间wlwcrazw1#
首先,停止网络读取线程的正确方法是关闭套接字。然后read/receive方法抛出一个异常并捕获它
当您在ide中单击stop按钮时,通常会立即(异常地)/终止jvm进程。我建议您在console中运行您的进程,并使用ctrl+c停止该进程并添加一个shutdownhook:
或者在eclipse中运行它,但在windows上停止taskkill,在linux上从命令行界面停止kill,以正常关闭jvm进程。
详见http://www.oracle.com/technetwork/java/javase/signals-139944.htmlhttps://docs.oracle.com/javase/7/docs/api/java/lang/runtime.html#addshutdownhook%28java.lang.thread%29