码迷,mamicode.com
首页 > 编程语言 > 详细

线程池使用实例

时间:2016-12-03 15:42:12      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:public   seconds   执行   login   关闭   return   time   更新   dha   

线程池:

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;
}
}

线程池使用实例

标签:public   seconds   执行   login   关闭   return   time   更新   dha   

原文地址:http://www.cnblogs.com/kanzghijie/p/6128645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!