假定线程池中有一些线程,一些是已终止的线程,一些是未终止的线程。
希望当所有这些线程都终止后退出主线程,主线程的代码该如何写?
主要是两点,一点是判断线程是否终止,另一点是等待线程终止。请给出具体代码。

解决方案 »

  1.   

    import java.util.LinkedList;
    import java.util.List;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;public class InvokeAllAndAnyTest {
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            ExecutorService pool = Executors.newCachedThreadPool();
            List<Callable<Integer>> tasks = new LinkedList<Callable<Integer>>();
            for (int i = 0; i < 8; ++i) {
                tasks.add(new Printer(i));
            }
            List<Future<Integer>> futures = pool.invokeAll(tasks); 
            
            System.out.println("...............................................");
            for (Future<Integer> future : futures) {
                System.out.println(future.get());
            }
            
            Integer result = pool.invokeAny(tasks);
            System.out.println("...............................................");
            System.out.println(result);
            
            pool.shutdown();
        }
    }class Printer implements Callable<Integer> {
        private int id;
        private static final int DELAY = 1000;    public Printer(int id) {
            this.id = id;
        }    public Integer call() {
            try {
                int times = 10;
                for (int i = 0; i < times; ++i) {
                    System.out.println("Id:" + id + " times:" + i);                Thread.sleep((int) (DELAY * Math.random()));
                }
            } catch (InterruptedException e) {
            }        return id;
        }
    }
      

  2.   

    最好是先了解Runnable, Callable, Future, FutureTask, ThreadPool等再做。
      

  3.   

    //下列方法分两个阶段关闭 ExecutorService。
    //第一阶段调用 shutdown 拒绝传入任务,然后调用 shutdownNow(如有必要)取消所有遗留的任务: 
     void shutdownAndAwaitTermination(ExecutorService pool) {
       pool.shutdown(); // Disable new tasks from being submitted
       try {
         // Wait a while for existing tasks to terminate
         if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
           pool.shutdownNow(); // Cancel currently executing tasks
           // Wait a while for tasks to respond to being cancelled
           if (!pool.awaitTermination(60, TimeUnit.SECONDS))
               System.err.println("Pool did not terminate");
         }
       } catch (InterruptedException ie) {
         // (Re-)Cancel if current thread also interrupted
         pool.shutdownNow();
         // Preserve interrupt status
         Thread.currentThread().interrupt();
       }
     }
      

  4.   

    只用join可不可以?主线程 {
      Thread t1 = ...
      Thread t2 = ...
      Thread t3 = ...  t1.start();
      t2.start();
      t3.start();  ...  t1.join();
      t2.join();
      t3.join();  //join语句执行完毕,主线程退出
      

  5.   


    用 join 是不行的join只是让其线程优先执行,而在join执行的时候其他线程处于等待状态等join 执行完后其他线程还是继续执行的
      

  6.   


    我觉得这个问题不存在,当执行t1.join()时,t2和t3并未处于等待状态,它们各自还是Runnable的,唯一处于等待状态的是主线程。而主线程不断处于等待状态也是有意义的:
    “希望当所有这些线程都终止后退出主线程”