我只想到了两种办法:1. 共享变量2. 采用任务链表
Java 里有没有现成的办法判定线程池里的工作任务做完吗?

解决方案 »

  1.   

    使用CyclicBarrier,这个可以为多个线程设置一个屏障。在多个线程没有完成之前,一直等待,如果最后一个完成了,则直接过去。
    或者使用for循环的future.get也可以。
      

  2.   

    我是使用系统自带的ExecutorService
      

  3.   

    用java.util.concurrent.atomic下面的原子类
      

  4.   

    像是用CyclicBarrier不适用,因为线程是放循环里的,做完又会继续做。只是总的线程的总数是可以确定,每个线程会跑多多少次却是不能确定的。
    Future.get返回值更加用不上。
    继续求解强解!
    附贴部分代码:
    package com.ifyours.statistics;import com.ifyours.statistics.fileoperator.FileProcess;
    import com.ifyours.statistics.util.DateTime;
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;import java.util.Date;
    import java.util.HashMap;
    import java.util.Map.Entry;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.logging.Level;
    import java.util.logging.Logger;public class ServiceExecutor {    public ServiceExecutor() throws IOException {
        }    public static void main(String[] args) {
            File filepath = new File("t:/ifyours/advert01/");
            Date date = DateTime.getDate("2011-08-14 08:30:00");
            // 查找出文件夹下待分析的文件列表
            HashMap<String, File> advertLogsFile = FileProcess.getAdvertFileList(filepath, date);
            ArrayList<Future<Integer>> al = new ArrayList<Future<Integer>>();
            boolean flag = true;        ExecutorService es = Executors.newFixedThreadPool(3);        for (Entry<String, File> entry : advertLogsFile.entrySet()) {
                if (entry.getKey().indexOf("ip") != -1) {
                 // 执行线性,依次统计
                    al.add((Future<Integer>) es.submit(new AnalyseAdvertLogs(entry.getValue(), date, date)));
                }
            }        while (flag) {    
                for (Future<Integer> fi : al) {
                 // 在这里我是想检测所有的返回对象是否已经做完,做完就可以执行一些写操作,完成后并把flag标志置false
                    if (fi.isDone()) {
                        try {
                            System.out.println(fi.get());
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ServiceExecutor.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (ExecutionException ex) {
                            Logger.getLogger(ServiceExecutor.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        }
    }
      

  5.   

    这个已经能满足你的需求了, concurrent包下面还有一些很好用的多线程的API, 已经可以满足绝大部分需求了, 没事多去翻翻官方API
      

  6.   

    我主题没有向大家说明白,上面这个仁兄,你看我中间的说明。CyclicBarries 只是设置一个屏障,所有的跑完一遍是可以的,但是线程还要重新继续跑。。不是的固定的.如何设置这个屏障呢?还请多指教
      

  7.   

    这个屏障可以重复使用 CountDownLatch  是不可重用的屏障
      

  8.   

    你可以再仔细看看 CycliBarries