zoukankan      html  css  js  c++  java
  • Java关闭Socket来终止线程

    Java代码:

    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();
        }
    }
  • 相关阅读:
    Docker笔记
    使用NextCloud搭建私有云盘
    docker轻量级管理工具
    docker仓库使用+harbor私有仓库部署
    防DDOS攻击解决方案
    MongoDB非关系型数据库
    监控磁盘使用率解决方案
    部署SonarQube代码质量检查7.7版本
    Jenkins的权限控制
    Jenkins分布式构建
  • 原文地址:https://www.cnblogs.com/frankyou/p/6520048.html
Copyright © 2011-2022 走看看