需要一种可中断的方式来监听工作线程中的UDP数据包

我正在开发一个Google Glass应用程序,它需要在工作线程中侦听UDP数据包(与发送UDP数据包的现有系统集成)。 我之前发过一个问题(见这里 )并收到一个答案,提供了一些如何做到这一点的指导。 使用其他讨论中的方法,我将有一个在DatagramSocket.receive()上被阻塞的工作线程。

进一步阅读告诉我,我需要能够按需启动/停止此操作。 所以这让我想到了我在这里发布的问题。 如何以能够中断(优雅地)UDP监听的方式执行上述操作? 有没有什么方法可以“很好地”让套接字断开来自另一个线程的receive()调用?

或者是否有另一种以可中断方式侦听UDP数据包的方法,因此我可以根据需要启动/停止侦听器线程以响应设备事件?

我的建议:

private DatagramSocket mSocket; @Override public void run() { Exception ex = null; try { // read while not interrupted while (!interrupted()) { .... mSocket.receive(...); // excepts when interrupted } } catch (Exception e) { if (interrupted()) // the user did it else ex = e; } finally { // always release release(); // rethrow the exception if we need to if (ex != null) throw ex; } } public void release() { // causes exception if in middle of rcv if (mSocket != null) { mSocket.close(); mSocket = null; } } @Override public void interrupt() { super.interrupt(); release(); } 

干净的切割,简单,总是释放和中断,在2种情况下干净利落。