sockect 编程线程池

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sockect 编程线程池相关的知识,希望对你有一定的参考价值。

一、 使用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 编程线程池的主要内容,如果未能解决你的问题,请参考以下文章

多线程编程

线程池与并行度

Java——线程池

Motan在服务provider端用于处理request的线程池

Java线程池详解

Java线程池详解