這是我做過什麼:
創建Interrupter
類
static private class Interrupter implements Runnable
{
private final Thread th1;
private volatile int wait=-1;
private Interrupter(Thread ith1)
{
th1=ith1;
}
public void run()
{
while(true)
{
try{
if(wait<0){ th1.join(); break; }
else{ Thread.sleep(wait); th1.interrupt(); wait=-1; }
} catch(Exception e){}
}
}
}
設置的Interrupter
Interrupter ir1=new Interrupter(Thread.currentThread());
Thread th1=new Thread(ir1);
th1.start();
// We need this so that later the wait variable
// can be passed in successfully
while(th1.getState()!=Thread.State.WAITING);
使用Interrupter
try{
ir1.wait=waitTimeout;
th1.interrupt();
// Receive on the socket
dc2.receive(bb2);
} catch(ClosedByInterruptException e){
// (Timed out)
Thread.interrupted();
dc2.close();
// Handle timeout here
// ...
// We need this so that later the wait variable
// can be passed in successfully
while(th1.getState()!=Thread.State.WAITING);
}
// Received packet
ir1.wait=-1;
th1.interrupt();
// We need this so that later the wait variable
// can be passed in successfully
while(th1.getState()!=Thread.State.WAITING);
Thread.interrupted();
我最近發現setSoTimeout()不適用於SocketChannel讀取,它看起來也不適用於DatagramChannels。爲什麼,我無法想象。有沒有理由不能使用DatagramSocket? – EJP 2013-03-11 12:03:08
沒理由。只是認爲DatagramChannel看起來更好。 – 2013-03-11 12:58:53
它確實,但它有這個奇怪的* lacuna。* – EJP 2013-03-12 03:41:42