我想设计一个多线程模块,我设置了两个类,设计如下:
ThreadConcurrentWoker.class:
public class ThreadConcurrentWoker<E, R> extends ThreadConcurrent<E, R> {
public ThreadConcurrentWoker(List<E> traget, CallableModel<E, R> callable) {
super.targetList = traget; // a list want to doing in thread.
super.callable = callable; // Custom callable object
super.results = new Vector<R>(); // get result in to this list
}
// this is doing Thread method
@Override
public List<R> concurrentExcute() throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(super.targetList.size());
CompletionService<R> completionService = new ExecutorCompletionService<R>(executor);
for (final E elememt : super.targetList) {
completionService.submit(new Callable<R>() {
@Override
public R call() throws Exception {
callable.setElement(elememt);
return callable.call();
}
});
}
int finishs = 0;
boolean errors = false;
while (finishs < super.targetList.size() && !errors) {
Future<R> resultFuture = completionService.take();
try {
super.results.add(resultFuture.get());
} catch (ExecutionException e) {
errors = true;
} finally {
finishs++;
}
}
return super.results;
}
}
CallableModel.class:
public abstract class CallableModel<E, V> implements Callable<V> {
private E element;
public E getElement() {
return element;
}
public void setElement(E element) {
this.element = element;
}
}
我希望像这样使用:
ThreadConcurrentWoker<FlowPendingCheckedBean, ResultBean> tCUtil =
new ThreadConcurrentWoker<>(test, new CallableModel<FlowPendingCheckedBean, ResultBean>() {
@Override
public ResultBean call() throws Exception {
// do something in here and return result.
}
});
try {
resultBeans = tCUtil.concurrentExcute();
} catch (Exception e1) {
log.error(e1.getMessage());
}
但是当我执行这个类时,它会在不同的线程中获得相同的数据。 导致数据库出现死锁。 我该如何改进呢?
答案 0 :(得分:0)
我试过了这个问题。记下笔记:
因为多线程使用相同的CallableModel
元素,所以当第一个线程在调用方法时,第二个线程进入setEelement
来改变元素,而这一次,第一个线程将获得第二个线程的元素。