Java通过关闭Socket终止线程
本文实例为大家分享了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(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)