0

我正在尝试实现一个多线程逻辑来同时发送 hsql 请求,并在所有线程结束时获得一个包含所有结果的列表。

我的线程类如下:

 public class QueryWorker implements Runnable {

    private static Query query;
    private List result;
    private Exception exception;
    private volatile boolean flag = false;

    public QueryWorker(Query query) {
        this.query = query;
    }

    public void run() {
        try {
            // System.out.println(method+" Start!!!");
            this.result = invokeMethod(this.query);
            this.flag = true;
            // System.out.println(method+" finished!!!");
        } catch (Exception e) {
            this.exception = e;
        }
    }

    public boolean isDaemon() {
        return false;
    }

    public void release() {
    }

    private static List invokeMethod(Query query) throws SecurityException,
            NoSuchMethodException, IllegalArgumentException,
            IllegalAccessException, InvocationTargetException,
            HibernateException {
        List result = query.list();
        return result;
    }

    public List getResult() {

        while (!flag) {
            System.out.println("blocked on the result");
            this.run();     
        }
        return result;
    }

    public void setResult(List result) {
        this.result = result;
    }

    public Exception getException() {
        return this.exception;
    }

} 

接下来我只是将查询添加到 ExecutorService。

...
ExecutorService executor = Executors.newFixedThreadPool(2);
            Runnable worker1 = new QueryWorker(q);
            executor.execute(worker1);
...
Runnable worker2 = new QueryWorker(q);
            executor.execute(worker2);
            executor.shutdown();        

            try {
                executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

                while (!executor.isTerminated()) {

                }

                list = ((QueryWorker) worker1).getResult();
                List list2 = ((QueryWorker) worker2).getResult();

                list.addAll(list2);
            } catch (InterruptedException e) {
                // send error somewhere
            }

问题是程序在我得到两个列表的结果之前就结束了。我还研究了如何使用 ThreadPoolExecutor,但我使用的是 java 1.4,所以我不能为了使用这个类而负担得起泛型的奢侈。

4

0 回答 0