IO阻塞时调用Interrupt()

beyondone 2005-12-16 06:20:06
各位大侠指点下.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)
{}
}

拜托各位了,谢谢!!!
...全文
384 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
beyondone 2005-12-18
  • 打赏
  • 举报
回复
自己顶
beyondone 2005-12-18
  • 打赏
  • 举报
回复
顶一个
beyondone 2005-12-17
  • 打赏
  • 举报
回复
多谢 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异常啊?
cenlmmx 2005-12-17
  • 打赏
  • 举报
回复
Thread.interrupt()将不起作用,因为线程将不会退出被阻塞状态.
cenlmmx 2005-12-17
  • 打赏
  • 举报
回复
调用阻塞该线程的套接字的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..." );

}

}
beyondone 2005-12-16
  • 打赏
  • 举报
回复
各位大侠指点下迷津,拜谢!

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧