java多线程管理 concurrent包用法详解,所有线程执行完成时再执行余下的内容

来源:互联网 发布:ipad版淘宝怎么看直播 编辑:程序博客网 时间:2024/05/19 08:24
//list 100条每组切分List<List<WendaQuestion>> allList = getAllList(insetQuestionList, 100);if (allList != null && !allList.isEmpty()) {ExecutorService service = Executors.newFixedThreadPool(10);CountDownLatch cd = new CountDownLatch(allList.size());for (int i = 0; i < allList.size(); i++) {service.submit(new QuestionExecutor(wendaQuestionDao,wendaQuestionCategoryRefDao, wendaRuleQuestionRefDao,allList.get(i), creator, wendaRule, cd));}try {cd.await();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}service.shutdown();}<pre name="code" class="java">//切分list
public List<List<WendaQuestion>> getAllList(List<WendaQuestion> list,
int size) {
List<List<WendaQuestion>> allList = new ArrayList<List<WendaQuestion>>();
List<WendaQuestion> subList = new ArrayList<WendaQuestion>();
Iterator<WendaQuestion> iter = list.iterator();
while (iter.hasNext()) {
subList.add((WendaQuestion) iter.next());
if (subList.size() == size) {
allList.add(subList);
subList = new ArrayList<WendaQuestion>();
}
}
allList.add(subList);
return allList;
}//线程static class QuestionExecutor extends Thread {
private WendaQuestionDao wendaQuestionDao;
private WendaQuestionCategoryRefDao wendaQuestionCategoryRefDao;
private WendaRuleQuestionRefDao wendaRuleQuestionRefDao;
private List<WendaQuestion> questionlist = new ArrayList<WendaQuestion>();
private String creator;
private WendaRule wendaRule;
CountDownLatch latch;


private QuestionExecutor(WendaQuestionDao wendaQuestionDao,
WendaQuestionCategoryRefDao wendaQuestionCategoryRefDao,
WendaRuleQuestionRefDao wendaRuleQuestionRefDao,
List<WendaQuestion> questionlist, String creator,
WendaRule wendaRule, CountDownLatch latch) {
super();
this.wendaQuestionDao = wendaQuestionDao;
this.wendaQuestionCategoryRefDao = wendaQuestionCategoryRefDao;
this.wendaRuleQuestionRefDao = wendaRuleQuestionRefDao;
this.questionlist = questionlist;
this.creator = creator;
this.wendaRule = wendaRule;
this.latch = latch;
}


public QuestionExecutor() {
}


public void run() {
this.insert();
latch.countDown();
}


public void insert() {
Iterator<WendaQuestion> it1 = questionlist.iterator();
while (it1.hasNext()) {
try {
WendaQuestion question = (WendaQuestion) it1.next();
wendaQuestionDao.insert(question);
// 增加问题分类关联
WendaQuestionCategoryRef categoryRef = new WendaQuestionCategoryRef();
categoryRef.setCatagoryId(wendaRule.getCategoryId());
categoryRef.setQuestionId(question.getId());
wendaQuestionCategoryRefDao.insert(categoryRef);
// 增加问题规则关联
WendaRuleQuestionRef ref = new WendaRuleQuestionRef();
ref.setCreator(creator);
ref.setCreatedAt(new Date());
ref.setGenerateId(wendaRule.getId());
ref.setQuestionId(question.getId());
wendaRuleQuestionRefDao.insert(ref);


} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}


}


}
}

0 0
原创粉丝点击