Java利用线程池实现处理Socket请求的小例子


任务描述,设计一个程序监听本机8790端口,在有socket连接到来时使用线程池创建处理线程,处理完后返回,主程序不参与服务。 

直接贴代码吧: 

主控Server

  1. package com.sdc.callmaxent.socket;  
  2. import java.io.IOException;  
  3. import java.net.ServerSocket;  
  4. import java.net.Socket;  
  5. import java.util.concurrent.ArrayBlockingQueue;  
  6. import java.util.concurrent.ThreadPoolExecutor;  
  7. import java.util.concurrent.TimeUnit;  
  8. import com.sdc.callmaxent.util.SystemConfig;  
  9. public class CallMaxentThreadPool {  
  10.     private static int produceTaskSleepTime = 20;  
  11.     private static int produceTaskMaskNumber = 10;  
  12.       
  13.     private static boolean flag = false;  
  14.       
  15.     public static void main(String[] args){  
  16.         startServ();  
  17.         //构造线程池   
  18.         System.out.println("Server listening......");  
  19.           
  20.         int port = SystemConfig.getInstance().getPort();  
  21.         ServerSocket serverSocket = null;  
  22.         try {  
  23.             serverSocket = new ServerSocket(port);  
  24.         } catch (IOException e1) {  
  25.             e1.printStackTrace();  
  26.         }  
  27.         Socket clientSocket = null;  
  28.         ThreadPoolExecutor threadPool = new ThreadPoolExecutor(  
  29.                 2,      //corePoolSize   
  30.                 4,      //maximumPoolSize   
  31.                 3,      //keepAliveTime   
  32.                 TimeUnit.SECONDS,   //unit   
  33.                 new ArrayBlockingQueue<Runnable>(3),  //workQueue   
  34.                 new ThreadPoolExecutor.DiscardOldestPolicy()//   
  35.         );   
  36.               
  37.         int i = 0;  
  38.         while(flag){  
  39.             //获得客户端请求   
  40.             try {  
  41.                 clientSocket = serverSocket.accept();  
  42.             } catch (IOException e) {  
  43.                 e.printStackTrace();  
  44.             }  
  45.             String task = "maxent_task@ " + i;  
  46.             System.out.println("put " + task);  
  47.             threadPool.execute(new CallMaxentThreadPoolTask(clientSocket));  
  48.             i++;  
  49.         }  
  50.     }  
  51.       
  52.     public static void startServ(){  
  53.         flag = true;  
  54.     }  
  55.       
  56.     public static void stopServ(){  
  57.         flag = false;  
  58.     }  
  59. }  

处理thread程序

  1. package com.sdc.callmaxent.socket;  
  2. import java.io.BufferedReader;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.io.OutputStream;  
  7. import java.io.PrintWriter;  
  8. import java.io.Serializable;  
  9. import java.net.Socket;  
  10. import com.sdc.callmaxent.util.FileUtil;  
  11. import com.sdc.callmaxent.util.SocketUtil;  
  12. import com.sdc.callmaxent.util.SystemConfig;  
  13. public class CallMaxentThreadPoolTask implements Runnable, Serializable{  
  14.      private static final long serialVersionUID = 0;     
  15.      private static int consumeTaskSleepTime = 20000;  
  16.        
  17.     private Socket socket;  
  18.     private InputStream clientInput;  
  19.     private OutputStream clientOutput;  
  20.        
  21.      CallMaxentThreadPoolTask(Socket socket){  
  22.         this.socket = socket;  
  23.           
  24.         try{  
  25.             this.clientInput = socket.getInputStream();  
  26.             this.clientOutput = socket.getOutputStream();  
  27.         }catch(IOException e){  
  28.             e.printStackTrace();  
  29.         }  
  30.      }  
  31.        
  32.      public void run(){  
  33.         BufferedReader breader = FileUtil.getBufferReader(new InputStreamReader(clientInput));  
  34.         try{  
  35.             //接收到客户端传来信息   
  36.             String strLine = breader.readLine();  
  37.             //参数切分   
  38.             String[] paramlist = strLine.split(",");  
  39.             String maxentPath = SystemConfig.getInstance().getMaxentPath();  
  40.               
  41.             String cmd = "cmd /c java -mx1024m -jar " + maxentPath + "/maxent.jar";  
  42.               
  43.             for(int i = 1;i<paramlist.length;i++){  
  44.                 cmd += " "+paramlist[i];  
  45.             }  
  46.             System.out.println(Thread.currentThread().getName());  
  47.             System.out.println("Maxent "+paramlist[0]+" is running, please wait!");  
  48.               
  49.             cmd += " novisible autorun";  
  50.               
  51.             Process p = Runtime.getRuntime().exec(cmd);  
  52.             p.waitFor();  
  53.             PrintWriter printWriter=new PrintWriter(clientOutput,true);   
  54.             printWriter.println("Finish!");  
  55.             System.out.println("Task "+paramlist[0]+" Finish!");  
  56.         }catch (IOException e) {      
  57.             e.printStackTrace();    
  58.         }catch(InterruptedException e){  
  59.          e.printStackTrace();  
  60.         }finally{  
  61.             FileUtil.close(clientInput);  
  62.             FileUtil.close(clientOutput);  
  63.             SocketUtil.close(socket);  
  64.         }  
  65.      }  
  66. }  

测试client端

  1. package com.sdc.callmaxent.socket;  
  2. import java.io.BufferedReader;    
  3. import java.io.IOException;    
  4. import java.io.InputStream;    
  5. import java.io.InputStreamReader;    
  6. import java.io.OutputStream;    
  7. import java.io.PrintWriter;    
  8. import java.net.Socket;    
  9. import java.net.UnknownHostException;    
  10. import com.sdc.callmaxent.util.FileUtil;  
  11. import com.sdc.callmaxent.util.SocketUtil;  
  12. import com.sdc.callmaxent.util.SystemConfig;  
  13. public class CallMaxentClient {  
  14.     public static void main(String[] args){  
  15.         try{  
  16.             System.out.println("Start sending......");  
  17.               
  18.             String ipAddress = SystemConfig.getInstance().getIP();  
  19.             int port = SystemConfig.getInstance().getPort();  
  20.               
  21.             Socket socket = SocketUtil.getSocket(ipAddress, port);  
  22.             BufferedReader bfReader = FileUtil.getBufferReader(new InputStreamReader(System.in));  
  23.             System.out.println("Waiting.....");   
  24.             String strLine = "1,environmentallayers=F:/test/maxent/testdata/layers,samplesfile=F:/test/maxent/testdata/bradypus.csv,outputdirectory=F:/test/maxent/testdata/outputs,togglelayertype=ecoreg,redoifexists";  
  25.             //String strLine = "environmentallayers=F:/test/maxent/testdata/layers,samplesfile=F:/test/maxent/testdata/bradypus.csv,outputdirectory=F:/test/maxent/testdata/outputs2,togglelayertype=ecoreg,redoifexists";   
  26.               
  27.             OutputStream outputStream = socket.getOutputStream();    
  28.             InputStream  inputStream = socket.getInputStream();  
  29.               
  30.             PrintWriter pw = new PrintWriter(outputStream,true);   
  31.               
  32.             pw.println(strLine);  
  33.             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));   
  34.             System.out.println(br.readLine());  
  35.         }catch (UnknownHostException e) {    
  36.              e.printStackTrace();    
  37.         }catch (IOException e) {    
  38.              e.printStackTrace();    
  39.         }   
  40.     }  
  41. }  

Thread Pool 执行优先级 

corePoolSize > workQueue > maximumPoolSize -> handler

相关内容