终止线程-stop

          
package com.infuq;
import java.net.*;
import java.io.*;

public class StopThread {
    public static void main(String[] args) throws Exception {

        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    Socket client = new Socket("127.0.0.1", 8080);
                    while (true) {
                        System.out.println("child thread....");
                    }
                } catch (Throwable t) {
                    System.out.println(t);
                }
            }
        };
        t.start();

        Thread.sleep(3000);
        // 终止线程
        t.stop();
    }
}
          
        
使用Python启动一个服务端
          
python3 -m http.server 8080
          
        
编译和执行StopThread
          
javac -d . StopThread.java
java com.infuq.StopThread
          
        
控制台输出
          
child thread....
child thread....
child thread....
child thread....
child thread....
child thread....
child thread....
child thread....
child thread....

java.lang.ThreadDeath
          
        
网络连接情况
          
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      1505/python3
tcp        0      0 127.0.0.1:8080          127.0.0.1:51680         ESTABLISHED 1505/python3
tcp6       0      0 127.0.0.1:51680         127.0.0.1:8080          ESTABLISHED 2004/java
          
        
          
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      1505/python3
tcp6       0      0 127.0.0.1:51680         127.0.0.1:8080          TIME_WAIT   -
          
        

调用stop方法, 需要注意线程持有的锁资源和网络资源等