如何写一个单独的线程处理某个方法
RT:
SSH2项目.因为某个方法处理速度慢,组长要求针对这个方法单独写一个线程来处理这个方法.
对线程只是了解.没有怎么用过线程.
有没有Demo或者一段代码就行.我想知道,怎么把线程加入到那个方法里面.结合起来用. 多线程 java
[解决办法]
新起个线程? 那你的web响应怎么办? 告诉用户“系统正在处理,啥时候好我也不知道,要等到线程结束”?如果不是这样还要起一个线程监控的刷新,间隔时间查询该线程是否结束然后告诉用户已经操作完毕。
更严重的是如果该操作直接影响其他的操作流程,那么整个流程的控制又要重新设计。所以尽量靠优化那个慢的方法,让他快一点,线程不一定能够解决你的问题。
[解决办法]
private static ThreadPoolExecutor executor=Executors.newCachedThreadPool();
public String saveTime() throws Exception {
executor.execute(new Runnable(){
public void run(){
User user = (User) session.get("user");
int userId = user.getUserId();
int companyId = (Integer) session.get("companyId");
Score sq1 = examService.findScoreById(scoreId);
int a = sq1.getSpendTime();
sq1.setSpendTime(a + Constant.AUTO_TIME);
examService.update(sq1);
System.out.println("select:" + select);
if (select != null && select.length() > 0) {
String[] selectString = select.split("@@@@@@@@");
Paper paper = this.examinationService.findPaperById(paperId);
Question question = null ;
UserAnswer userAnswer = null ;
for (int i = 0; i < selectString.length; i++) {
String sel = selectString[i];
if (sel != null && sel != "") {
String sel1[] = sel.split("&&&&&&&&");
if (isNum(sel1[0])) {
this.examinationService.delete(userId, paperId, Integer.parseInt(sel1[0]), scoreId, companyId);
question = this.examinationService.findQuestionById(Integer.parseInt(sel1[0]));
userAnswer = new UserAnswer();
userAnswer.setPaper(paper);
userAnswer.setQuestion(question);
userAnswer.setUser(user);
userAnswer.setUserAnswer(sel1[1]);
userAnswer.setScoreId(scoreId);
userAnswer.setCompanyId(companyId);
examinationService.save(userAnswer);
}
}
}
}
ok = true;
}
});
return "saveTime";
}