首页 > 代码库 > sockect 编程线程池

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 编程线程池