java多线程异步任务,java使用线程池完成异步任务

管理系统中,在执行耗时的操作时阻塞用户主线程。用户界面迟迟得不到返回信息,甚至是超时;在这种业务场景下可以使用异步任务

用户发出了一个耗时操作请求,主线程立即return

如果当前异步任务没有被执行完,用户再次发起提示“有任务正在执行“,直到当前任务执行完毕才允许再次执行

提供中断当前正在执行的任务功能

先看看效果

4dd0bc3d7fd9?from=singlemessage

gif.gif

java代码

package io.renren.modules.generator.service.impl;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

import com.baomidou.mybatisplus.mapper.Wrapper;

import com.baomidou.mybatisplus.plugins.Page;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import com.hankcs.hanlp.HanLP;

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import io.renren.common.utils.PageUtils;

import io.renren.common.utils.Query;

import io.renren.common.utils.R;

import io.renren.modules.backstage.service.ArticleService;

import io.renren.modules.generator.dao.KeywordDao;

import io.renren.modules.generator.entity.KeywordEntity;

import io.renren.modules.generator.service.KeywordService;

import io.renren.modules.main.entity.Article;

import io.renren.modules.websocket.handler.MyChannelHandlerPool;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.math.BigDecimal;

import java.text.DecimalFormat;

import java.util.List;

import java.util.Map;

import java.util.concurrent.*;

@Service("keywordService")

public class KeywordServiceImpl extends ServiceImpl implements KeywordService {

@Autowired

private ArticleService articleService;

private KeywordDao getMapper() {

return this.baseMapper;

}

//单线程的线程池

private ExecutorService executor = Executors.newSingleThreadExecutor();

private ExecutorService executorFlag = Executors.newSingleThreadExecutor();

private Future> future;

private FutureTask getTask() {

FutureTask booleanFutureTask = new FutureTask(new Callable() {

@Override

public Boolean call() {

List textAll = articleService.getMapper().getTextAll();

for (Article article : textAll) {

List keywordList = HanLP.extractKeyword(article.getContent(), 5);

String[] arr = keywordList.toArray(new String[keywordList.size()]);

String join = String.join(",", arr);

KeywordEntity keyWord = new KeywordEntity();

keyWord.setKeyWord(join);

keyWord.setArticleId(article.getNewId().intValue());

keyWord.setType(article.getType());

getMapper().insert(keyWord);

}

return true;

}

});

return booleanFutureTask;

}

@Override

public PageUtils queryPage(Map params) {

//查询参数

String key = (String) params.get("key");

//Wrapper

Wrapper wrapper = new EntityWrapper().like("key_word", key);

//解析分页参数

Page pa = new Query(params).getPage();

//设置总数

pa.setTotal(this.selectCount(wrapper));

//分页查询

Page page = this.selectPage(

pa,

wrapper

);

//构造pageBean

return new PageUtils(page);

}

@Override

public R generateKeyWord() {

String msg;

if (future == null || future.isDone()) {

future = executor.submit(getTask());

msg = "开始新任务";

//子线程去推送生成进度

executorFlag.submit(() -> {

while (!(future == null || future.isDone())) {

MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(getProgress().toString()));

}

});

} else {

msg = "任务未结束!不能重复生成,请等待片刻";

}

System.out.println("============执行后===================");

System.out.println(future.isCancelled());

System.out.println(future.isDone());

System.out.println("=============执行后==================");

return R.ok(msg);

}

@Override

public R truncateKeyWord() {

if (future != null && !future.isDone()) {

//结束生成任务

future.cancel(true);

}

baseMapper.truncateKeyWord();

return R.ok();

}

@Override

public Float getProgress() {

return articleService.getMapper().getAllIdCount().floatValue();

}

}

关键点

通过future.isDone() 判断当前任务是否完成

通过future.cancel(true) 终止当前正在执行的任务

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值