各位大侠指点下.Interrupt()好像不能停止一个正处于IO阻塞中的线程,且无法生成InterruptException.那么一个线程如果因为IO操作处于阻塞状态时,该怎样来中止它呢?下面是我写的一段代码:class MM extends JFrame implements Runnable{......}addWindowListener(new WindowAdapter()//给MM添加监视器
{
  public void windowClosing(WindowEvent we)
  {
    try
    {
      serverwork.interrupt();    //serverwork的定义:Thread serverwork=new Thread(MM)
      System.exit(1);
    }
    catch(Exception e)
    {}
  }
});public void run()    //MM中的Run方法
{
  try
  {
ss=new ServerSocket(4001);    //ss是MM中的一个ServerSocket
Socket s=ss.accept();
while(true)
{
byte[] temp=new byte[100];
InputStream sis=s.getInputStream();
try
{
                           sis.read(temp);    //进行IO操作时阻塞,WindowListener()中调用
                                              //serverwork.interrupt()也无法终止它
jtareceive.append("Message from client : "+(new String(temp))+'\n'); }
catch(Exception e)//调用serverwork.interrupt()后捕捉不到interruptexcep.
{
sis.close();
s.close();
ss.close();
return;
}
}
  }
  catch(Exception e)
  {}
}拜托各位了,谢谢!!!

解决方案 »

  1.   

    调用阻塞该线程的套接字的close()方法。在这种情形下,如果线程被I/O操作阻塞,该线程将接收到一个SocketException异常,这与使用interrupt()方法引起一个InterruptedException异常被抛出非常相似。唯一要说明的是,必须存在socket的引用(reference),只有这样close()方法才能被调用import java.net.*;import java.io.*;class Example5 extends Thread {  volatile boolean stop = false;  volatile ServerSocket socket;  public static void main( String args[] ) throws Exception {    Example5 thread = new Example5();   System.out.println( "Starting thread..." );   thread.start();   Thread.sleep( 3000 );   System.out.println( "Asking thread to stop..." );   thread.stop = true;   thread.socket.close();   Thread.sleep( 3000 );   System.out.println( "Stopping application..." );   System.exit( 0 );  }  public void run() {    try {      socket = new ServerSocket(7856);    } catch ( IOException e ) {     System.out.println( "Could not create the socket..." );      return;    }    while ( !stop ) {     System.out.println( "Waiting for connection..." );      try {       Socket sock = socket.accept();      } catch ( IOException e ) {      System.out.println( "accept() failed or interrupted..." );      }    }   System.out.println( "Thread exiting under request..." );  }}
      

  2.   

    Thread.interrupt()将不起作用,因为线程将不会退出被阻塞状态.
      

  3.   

    多谢 cenlmmx(学海无涯苦作舟) 大侠的指点!是不是可以总结到一个原则:当thread被阻塞时,应该通过对引起阻塞的object进行操作,从而来达到结束阻塞,终止被阻塞thread的目的?而直接对被阻塞的thread进行终止是无效的?我在文档中thread.interrupt()的描述里找到了这段话:
    If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException照这段话,调用被阻塞thread.interrupt()应该还是能够起作用,并会抛出interrupt异常啊?