码迷,mamicode.com
首页 > 编程语言 > 详细

sockect 编程线程池

时间:2017-05-16 13:04:16      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:输入   word   套接字   out   pretty   his   null   info   调用   

一、 使用Callable 接口

public class DatePoolServer { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(50);// 创建50大小的线程池 try (ServerSocket server = new ServerSocket(7456)) { while (true) { Socket connection = server.accept(); Callable<Void> task = new DateTask(connection); Void 是java.lang.void pool.submit(task);//将任务提交到线程池,等待调用 } } catch (IOException e) { e.printStackTrace(); } } public class DateTask implements Callable<Void> { private Socket connection; public DateTask(Socket connection) { this.connection = connection; } @Override public Void call() {//在此任务被调用的是调用此方法 Void 是java.lang.void
      
      long threadId = Thread.currentThread().getId();
      String name =Thread.currentThread().getName();
      System.err.println("当前线程的id"+threadId+"当前线程的名字"+name);
Writer writer; try { writer = new OutputStreamWriter(connection.getOutputStream()); Date now = new Date(); writer.write(now.toString() + "\r\n"); writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (connection != null) connection.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } } }

二、 使用Runnable 接口  
      服务器:
      private ServerSocket serverSocket = null;
      private Socket socket = null;

      serverSocket = new ServerSocket(port);
      Socket socket = null;

      ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
      while(true){
        socket = serverSocket.accept();
        Runnable thread = new ThreadedServer(socket);
        fixedThreadPool.submit(thread);

      }
      
  
      服务线程类:
      public class ThreadedServer implements Runnable {
      private Socket socket = null;
     
private static OutputStream OUT = null; // 声明输出流
      private InputStream in = null; // 声明输入流
 
      public ThreadedServer(Socket s) throws Exception {
    socket = s;
    try {
    OUT = socket.getOutputStream();// 返回此套接字的输出流
    in = socket.getInputStream();// 返回此套接字的输入流
    } catch (Exception e) {
     e.printStackTrace();
    socket.shutdownInput();
    socket.shutdownOutput();
    socket.close();
    LOG.info("异常关闭socket----->" + socket);
}
}
       public void run(){
        long threadId = Thread.currentThread().getId();
        String name =Thread.currentThread().getName();
        System.err.println("当前线程的id"+threadId+"当前线程的名字"+name);

        }
      
      
}





sockect 编程线程池

标签:输入   word   套接字   out   pretty   his   null   info   调用   

原文地址:http://www.cnblogs.com/JimCalark/p/6860460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!