您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java怎样中断一个运行中的线程(3)

2024/3/2 3:36:36发布13次查看
中断i/o操作
然而,如果线程在i/o操作进行时被阻塞,又会如何?i/o操作可以阻塞线程一段相当长的时间,特别是牵扯到网络应用时。例如,服务器可能需要等待一个请求(request),又或者,一个网络应用程序可能要等待远端主机的响应。
如果你正使用通道(channels)(这是在java 1.4中引入的新的i/o api),那么被阻塞的线程将收到一个 closedbyinterruptexception异常。如果情况是这样,其代码的逻辑和第三个例子中的是一样的,只是异常不同而已。
但是,你可能正使用java1.0之前就存在的传统的i/o,而且要求更多的工作。既然这样,thread.interrupt()将不起作用,因为线程将不会退出被阻塞状态。listing d描述了这一行为。尽管interrupt()被调用,线程也不会退出被阻塞状态。
listing d import java.io.*; class example4 extends thread { public static void main( string args[] ) throws exception { example4 thread = new example4(); system.out.println( "starting thread..." ); thread.start(); thread.sleep( 3000 ); system.out.println( "interrupting thread..." ); thread.interrupt(); thread.sleep( 3000 ); system.out.println( "stopping application..." ); //system.exit( 0 ); } public void run() { serversocket socket; try { socket = new serversocket(7856); } catch ( ioexception e ) { system.out.println( "could not create the socket..." ); return; } while ( true ) { system.out.println( "waiting for connection..." ); try { socket sock = socket.accept(); } catch ( ioexception e ) { system.out.println( "accept() failed or interrupted..." ); } } } }
很幸运,java平台为这种情形提供了一项解决方案,即调用阻塞该线程的套接字的close()方法。在这种情形下,如果线程被i/o操作阻塞,该线程将接收到一个socketexception异常,这与使用interrupt()方法引起一个interruptedexception异常被抛出非常相似。
唯一要说明的是,必须存在socket的引用(reference),只有这样close()方法才能被调用。这意味着socket对象必须被共享。listing e描述了这一情形。运行逻辑和以前的示例是相同的。
listing e 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..." ); } }
以下是运行listing e中代码后的输出:
starting thread... waiting for connection... asking thread to stop... accept() failed or interrupted... thread exiting under request... stopping application...
多线程是一个强大的工具,然而它正呈现出一系列难题。其中之一是如何中断一个正在运行的线程。如果恰当地实现,使用上述技术中断线程将比使用java平台上已经提供的内嵌操作更为简单。
以上就是java怎样中断一个运行中的线程(3)的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product