在进入方法时启动另一个线程计时,到十秒时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
}写得很粗,意思到了。不知道有没有什么更好的方法

解决方案 »

  1.   

    在方法内创建计时线程,是当主线程执行in.reada()是开始计时,是不是把in.read()写到timer中呢?时间到了就interrupt()中断线程,同时thread.setDaeman(true) 这样对嘛?
      

  2.   

    public class Test {
    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();
    }
    }这回该满意了吧!^_^