ThreadPoolExecutor的实现发送消息
1.场景:
最近在做发送消息的时,为了提高效率,并让CPU充分利用,利用线程池发送消息
2.代码实现
public class TestThreadPoolExecutor {
private static ThreadPoolExecutor threadPoolExecutor;
static {
ThreadFactory factory = new Builder().namingPattern("example-schedule-pool-%d").build();
threadPoolExecutor = new ThreadPoolExecutor(100,
100, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(), factory, new AbortPolicy());
threadPoolExecutor.allowCoreThreadTimeOut(true);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
threadPoolExecutor.shutdown();
}
}));
}
public static Boolean sendMsg(int i) {
Future<Boolean> submit = threadPoolExecutor.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return doCommonSend(i);
}
});
try {
return submit.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return false;
}
public static boolean doCommonSend(int a) {
System.out.println("doCommonSend" + a);
if (a == 0) {
return false;
}
return true;
}
public static void main(String[] args) {
for (int i = 0; i < 10000000; i++) {
sendMsg(i);
}
}
结果