本文实例为大家分享了Java关闭Socket实现终止线程的具体代码,供大家参考,具体内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
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();
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。