亲宝软件园·资讯

展开

Java终止线程 Java通过关闭Socket终止线程

FrankYou 人气:0
想了解Java通过关闭Socket终止线程的相关内容吗,FrankYou在本文为您仔细讲解Java终止线程的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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();
  }
}

加载全部内容

相关教程
猜你喜欢
用户评论