在进入方法时启动另一个线程计时,到十秒时interrupt()这个等待输入线程。getInputStream(InputStream in) {
// 创建计时线程
Runnable timer = new YourOwnTimer(Thread.getCurrentThread());
Thread thread = new Thread(timer);
thread.start();
// 加一层try catch 为了InterruptedException
in.read();
thread.interrupt(); // 读到了自然就不用再打断了
// catch
}写得很粗,意思到了。不知道有没有什么更好的方法
// 创建计时线程
Runnable timer = new YourOwnTimer(Thread.getCurrentThread());
Thread thread = new Thread(timer);
thread.start();
// 加一层try catch 为了InterruptedException
in.read();
thread.interrupt(); // 读到了自然就不用再打断了
// catch
}写得很粗,意思到了。不知道有没有什么更好的方法
class MyTimer implements Runnable{
private long startTime = 0;
private long endTime = 0;
// bStart = true,表示超时,false表示继续等待
private boolean bStart = false;
private long waitTime = 5*1000;
public MyTimer(){}
public boolean getBStart(){
return this.bStart;
}
public void setBStart(){
while(bStart == true){
endTime = System.currentTimeMillis();
if(endTime-startTime>=waitTime)
this.bStart = false;
else
this.bStart = true;
}
}
/* (非 Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
this.setBStart();
Thread.interrupted();
}
}
public void getInfo(InputStream in)
{
MyTimer timer = new MyTimer();
Thread thread = new Thread(timer);
thread.setDaemon(true);
thread.start();
}
}这回该满意了吧!^_^