Java实现的并发任务处理实例

网友投稿 203 2023-07-25


Java实现的并发任务处理实例

本文实例讲述了java实现的并发任务处理方法。分享给大家供大家参考,具体如下:

public void init() {

super.init();

this.ioThreadPool = new ThreadPoolExecutor(50, 50, Long.MAX_VALUE, TimeUnit.SECONDS, new java.util.concurrent.LinkedTransferQueue(), new ThreadFactory() {

AtomicLong id = new AtomicLong();

@Override

public Thread newThread(final Runnable r) {

Thread t = new Thread(new Runnable() {

@Override

public void run() {

try {

r.run();

} catch (RuntimeException e) {

logger.error("执行IO异常", e);

throw e;

}

}

});

t.setDaemon(true);

t.setName("FootballService-IO-" + id.getAndIncrement());

return t;

}

});

}

//从fdate到tdate, 结果: 日期 30个区的创建角色总和

public Map countCreateRole(String fdate, String tdate, final String channel, Map gameConfig) throws Exception {

// 只读数据不需要处理并发

final Map param = new HashMap();

param.put("fdate", fdate);

param.put("tdate", tdate);

param.put("channel", channel);

final Map date_count = new HashMap();

final List zones = (List) gameConfig.get("areas");

Set dateSet = JdbcTool.getDateRangeByDay(fdate, tdate, "yyyy-MM-dd");

List> tasks = new ArrayList<>(zones.size());

for (String date : dateSet) {

final String _date = date;

tasks.add(publicThread.submit(new Callable() {

@Override

public Void call() {

final AtomicLong count = new AtomicLong();

List> subTasks = new ArrayList<>(zones.size());

for (String _zone : zones) {

final String zone = _zone;

subTasks.add(ioThreadPool.submit(new Callable() {

@Override

public Void call() throws Exception {

JdbcTemplate _jdbcTemplate = dataSourceManager.getJdbcTemplate(zone);

String database = dataSourceManager.getDatabase(zone);

String _count = mget(CacheConstant.RZRoleCreateCount, zone + "#" + _date + "#" + channel + "#");

if (_count == null) {

StringBuilder sb = new StringBuilder();

sb.append("SELECT count(roleId) as count ");

sb.append("from " + database + "_log.role ");

sb.append("WHERE DATE(createTime)='" + _date + "' ");

if (param.get("channel") != null) {

sb.append(" AND channelId = '" + channel + "' ");

}

long queryForLong = _jdbcTemplate.queryForLong(sb.toString());

count.addAndGet(queryForLong);

mput(CacheConstant.RZRoleCreateCount, zone + "#" + _date + "#" + channel + "#", queryForLong + "");

} else {

count.addAndGet(Long.valueOf(_count));

}

return null;

}

}));

}

for (Future task : subTasks) {

try {

task.get();

} catch (Exception e) {

throw new RuntimeException(e);

}

}

synchronized (date_count) {

date_count.put(_date, count.get());

}

return null;

}

}));

}

for (Future task : tasks) {

task.get();

}

return date_count;

}

@PreDestroy

public void destroy() {

this.ioThreadPool.shutdownNow();

}

希望本文所述对大家java程序设计有所帮助。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Bootstrap每天必学之下拉菜单
下一篇:dubbo接口测试 - 了解如何进行高效的接口测试
相关文章

 发表评论

暂时没有评论,来抢沙发吧~