Java多线程导致数据库死锁(Java 7)
Posted
技术标签:
【中文标题】Java多线程导致数据库死锁(Java 7)【英文标题】:Java multi-threading cause database deadlock (Java 7) 【发布时间】:2018-11-09 23:02:34 【问题描述】:我想设计一个多线程模块,我设置了两个类,设计如下:
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());
但是当我执行这个类时,它会在不同的线程中得到相同的数据。 导致数据库会出现死锁。 我该如何改进它?
【问题讨论】:
【参考方案1】:我试过这个问题。写下笔记:
由于多线程使用相同的CallableModel
元素,所以当第一个线程调用方法时,第二个线程进入setEelement
改变元素,这一次,第一个线程将获得第二个线程的元素。
【讨论】:
以上是关于Java多线程导致数据库死锁(Java 7)的主要内容,如果未能解决你的问题,请参考以下文章