这就是我所做的:
创建一个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();