java socket伪异步IO式

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;


/**

 * 伪异步IO模式:线程池

 * @author 

 *

 */

public class TimeServer {

public static void main(String[] args) {

int port = 8080;

if(null != args && args.length > 0) {

try {

port = Integer.parseInt(args[0]);

} catch (NumberFormatException e) {

e.printStackTrace();

}

}

ServerSocket server = null;

try {

server = new ServerSocket(port);

System.out.println("the timeserver is start in port "+port);

Socket socket = null;

//创建IO任务线程池

TimeServerHandlerExecutorPool singleExecutor = new TimeServerHandlerExecutorPool(50, 10000);

while(true) {

socket = server.accept();

singleExecutor.execute(new TimeServerHandler(socket));

}

} catch (IOException e) {

e.printStackTrace();

} finally{

if(null != server) {

System.out.println("the timeserver is closed");

try {

server.close();

} catch (IOException e) {

e.printStackTrace();

} finally{

server = null;

}

}

}

}

}

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.ThreadPoolExecutor;

import java.util.concurrent.TimeUnit;


/**

 * 伪异步IO

 * @author

 *

 */

public class TimeServerHandlerExecutorPool {

private ExecutorService executor;

public TimeServerHandlerExecutorPool(int maxPoolSize, int queueSize) {

executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), maxPoolSize, 120L, TimeUnit.SECONDS, new ArrayBlockingQueue<java.lang.Runnable>(queueSize));

}

public void execute(java.lang.Runnable task) {

executor.execute(task);

}

}


你可能感兴趣的:(java socket伪异步IO式)