Java通过关闭Socket终止线程
程序员文章站
2024-03-01 11:17:04
本文实例为大家分享了java关闭socket实现终止线程的具体代码,供大家参考,具体内容如下
package threads;
import java.io...
本文实例为大家分享了java关闭socket实现终止线程的具体代码,供大家参考,具体内容如下
package threads; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstreamreader; import java.net.socket; /** * created by frank */ public class stopclose extends thread { protected socket io; public void run() { try { io = new socket("java.sun.com", 80); bufferedreader is = new bufferedreader(new inputstreamreader(io.getinputstream())); system.out.println("stopclose reading"); /** * 死锁,因为读取响应之前,http责成客户端发送一个请求(像get/http/1.0)和一个空行 */ string line = is.readline(); /** * 所以我们永远不可能到达这里 */ system.out.printf("stopclose finished after reading %s!", line); } catch (ioexception ex) { system.out.println("stopclose terminating:" + ex); } } public void shutdown() throws ioexception { if (io != null) { synchronized (io) { io.close(); } } system.out.println("stopclose.shutdown() complete"); } public static void main(string[] args) throws interruptedexception, ioexception { stopclose t = new stopclose(); t.start(); sleep(1000*5); t.shutdown(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。