线程池使用实例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程池使用实例相关的知识,希望对你有一定的参考价值。

线程池:

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

以上是关于线程池使用实例的主要内容,如果未能解决你的问题,请参考以下文章

#私藏项目实操分享#Java多线程下载器项目实例之线程池

java 线程池 使用实例

使用线程池优化多线程编程

线程池使用实例

多线程简单实例线程池

Java并发编程:Java线程池核心ThreadPoolExecutor的使用和原理分析