代码之家  ›  专栏  ›  技术社区  ›  J. Hu

Java多线程导致数据库死锁(Java 7)

  •  0
  • J. Hu  · 技术社区  · 7 年前

    我想设计一个多线程模块,我设置了两个类,设计如下:

    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 回复  |  直到 7 年前
        1
  •  0
  •   J. Hu    7 年前

    我试过这个问题。写下笔记:

    因为多线程使用相同的 CallableModel 元素,因此当调用方法中的第一个线程时,第二个线程进入 setEelement 若要更改元素,这次,第一个线程将获取第二个线程的元素。