Java terminates the thread by closing Socket
- 2020-06-19 10:24:07
- OfStack
This article shares the specific code for Java to close Socket to terminate the thread, for your reference, the specific content is as follows
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");
/**
* Deadlock because before reading the response, HTTP Instruct client to send 1 A request (like GET/HTTP/1.0 ) and 1 A blank line
*/
String line = is.readLine();
/**
* So we'll never get here
*/
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();
}
}