线程池:
package com.mainserver;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.config.ServerConfig;
/**
* 业务线程池
* */
public class ThreadBusiness {
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadBusiness.class);
private final ExecutorService executorService;
private static ThreadBusiness INSTANCE = new ThreadBusiness(ServerConfig.getInstance().getHandleThreadNumber());
public static ThreadBusiness getInstance() {
return INSTANCE;
}
private ThreadBusiness(int threadNumber) {
executorService = Executors.newFixedThreadPool(threadNumber);
}
/**
* 执行线程
* */
public void execute(Runnable runnable) {
if (null == runnable) {
return ;
}
executorService.execute(runnable);
}
/**
* 关闭线程池
*/
public void shutdown() {
try {
executorService.shutdown();
while (executorService.awaitTermination(1, TimeUnit.SECONDS)) {
LOGGER.info("server executor stop");
break;
}
} catch (InterruptedException e) {
LOGGER.error("server awaitTermination exception: {}", e);
}
}
}
执行线程:
public class ServerNetHandler extends SimpleChannelInboundHandler<ReqPacket> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("get new connect..");
writeData(ctx.channel());
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ReqPacket reqPacket) throws Exception {
if (!(reqPacket instanceof ReqPacket)) {
if (ServerConfig.getInstance().ismScreepPrint()) {
System.out.println("it isnt my type");
}
return;
}
RequestHandler handler = new RequestHandler(reqPacket);
ThreadBusiness.getInstance().execute(handler);
}
}
线程业务:
public class RequestHandler implements Runnable {
private static final Logger log = LoggerFactory.getLogger(RequestHandler.class);
private ReqPacket req;
public RequestHandler(ReqPacket reqPacket) {
this.req = reqPacket;
}
@Override
public void run() {
switch (req.header.cmd) {
case eCommand.LOGIN_SERVER_LIST_VALUE:
// 获取登录服列表
writeLoginList(req);
break;
case eCommand.SYS_ADDANDUPDATE_SERVERLIST_VALUE:
// 增加和更新登录服务器列表
sysAddAndUpdateServerList(req);
break;
default:
break;
}
}