我有3个任务,需要并行执行,也就是同时执行.每个任务一个执行结果.
模拟一下:
任务1:打印一条语句,然后等待10秒.返回一个整数1.
任务2:打印一条语句,然后等待8秒.返回一个整数1.
任务3:打印一条语句,然后等待5秒.返回一个整数1.等上面都返回值之后,执行任务4.打印一条语句.问题是:
如何让3个任务同时执行? 我想到的是多线程,除了多线程还有其他办法吗?
如何确保3个任务都执行完毕之后,才会执行下面的任务?

解决方案 »

  1.   

    一个共用计数器,每个线程执行完毕计数器加1
    主线程调用3个线程,然后
    while(true) {
        if (计数器>=3) break;
        Thread.sleep(100);
    }
      

  2.   

    可以用 ExecutorService + Callable + Future 来解决:
    public class CallableTest implements Callable<Integer> {

    private final long waitTime;
    private final int taskId;

    public CallableTest(long waitTime, int taskId) {
    this.waitTime = waitTime;
    this.taskId = taskId;
    } public Integer call() throws Exception {
    System.out.println("Hello, this is task: "+this.taskId);
    Thread.sleep(this.waitTime);
    return 1;
    }}public class CallableDriver { public static void main(String[] args) {

    ExecutorService  executor = Executors.newFixedThreadPool(3);
           
    CallableTest task1 = new CallableTest(10*1000l, 1);
    CallableTest task2 = new CallableTest(8*1000l, 2);
    CallableTest task3 = new CallableTest(5*1000l, 3);

            Future<Integer> future1= executor.submit(task1);
            Future<Integer> future2= executor.submit(task2);
            Future<Integer> future3= executor.submit(task3);
            
            while(true){
             if(future1.isDone() && future2.isDone() && future3.isDone()){
             break;
             }
            }
           
            try {
    System.out.println("Return Value from task1: " + future1.get());
    System.out.println("Return Value from task2: " + future2.get());
    System.out.println("Return Value from task3: " + future3.get());
    } catch (InterruptedException e) {
    e.printStackTrace();
    } catch (ExecutionException e) {
    e.printStackTrace();
    }

    System.out.println("All tasks finished");      
          
    }
    }
      

  3.   

    OK,  while(true){
                if(future1.isDone() && future2.isDone() && future3.isDone()){
                    break;
                }
            }这段代码会等所有的任务都结束,然后执行下面的任务。
      

  4.   

    搜索barrier,找个现成的用,代码很多不贴了。
      

  5.   

    class ThreadTest {
    interface Task extends Runnable {
    Object getResult();
    } public static void main(String[] args) throws InterruptedException {
    Task task1, task2, task3;
    task1 = new Task() {
    @Override
    public void run() {
    try {
    System.out.println("t1 will die after 5 seconds");
    Thread.sleep(5000);
    System.out.println("t1 returns " + getResult());
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    } @Override
    public Object getResult() {
    return 1;
    }
    };
    task2 = new Task() {
    @Override
    public void run() {
    try {
    System.out.println("t2 will die after 8 seconds");
    Thread.sleep(8000);
    System.out.println("t2 returns " + getResult());
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    } @Override
    public Object getResult() {
    return 2;
    }
    };
    task3 = new Task() {
    @Override
    public void run() {
    try {
    System.out.println("t3 will die after 10 seconds");
    Thread.sleep(10000);
    System.out.println("t3 returns " + getResult());
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    } @Override
    public Object getResult() {
    return 3;
    }
    };
    Thread t1, t2, t3;
    t1 = new Thread(task1);
    t2 = new Thread(task2);
    t3 = new Thread(task3);
    t1.start();
    t2.start();
    t3.start();
    t1.join();
    t2.join();
    t3.join();
    System.out.println("All three threads have died");
    }}写了个奇怪的东西出来……
      

  6.   

    我也觉得用join  可惜我理解不够透彻 不知道对不对
      

  7.   

    public class CallableTest implements Callable<Integer> {
        
        private final long waitTime;
        private final int taskId;
        
        //构造器,初始化waitTime and taskId
        public CallableTest(long waitTime, int taskId) {
            this.waitTime = waitTime;
            this.taskId = taskId;
        }
        
        //实现Callable接口的call方法,会在线程池submit(this)的时候调用本方法
        public Integer call() throws Exception {
            System.out.println("Hello, this is task: "+this.taskId);    
            Thread.sleep(this.waitTime);
            return taskId;
        }}public class CallableDriver {    public static void main(String[] args) {
            
    //创建1个线程池,长度为3
            ExecutorService  executor = Executors.newFixedThreadPool(3);
            
            CallableTest task1 = new CallableTest(20*1000l, 1);
            CallableTest task2 = new CallableTest(16*1000l, 2);
            CallableTest task3 = new CallableTest(2*1000l, 3);
            
    //启动3个线程,调用各自的call(),此时call()已经开始执行
            Future<Integer> future1= executor.submit(task1);
            Future<Integer> future2= executor.submit(task2);
            Future<Integer> future3= executor.submit(task3);
            
    //循环可以说省略吗?我注释了没影响
    //        while(true){
    //            if(future1.isDone() && future2.isDone() && future3.isDone()){
    //                break;
    //            }
    //        }
           
            try {
        //当各自执行完以后打印各自的结果
                System.out.println("Return Value from task1: " + future1.get());
                System.out.println("Return Value from task2: " + future2.get());
                System.out.println("Return Value from task3: " + future3.get());            
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            
            System.out.println("All tasks finished");  
    //关闭线程池
            executor.shutdown();
          
        }
    }
    看了下API,加上了自己的注释,,,中间的while(true)监控如果不写会不会带来什么异常?
      

  8.   

    看了下API,加上了自己的注释,,,中间的while(true)监控如果不写会不会带来什么异常?不会,我那样写只是为了让代码的意图看起来更明显。结果是一样的。
      

  9.   


    用join就不对了,用了join就等于串行运行了。
    楼主可以去搜一下“主线程等待子线程完成”,会有你要的答案。
      

  10.   

    java并发集合  CyclicBarrier  就是为了做这种事情的...超级简单..不会出错
      

  11.   


    t1.join()只是指调用的线程(这里是main)会等t1执行完再执行自身的后续工序,并不会对其他的线程产生影响,该并发继续并发
    t1.join();t2.join();t3.join();就是等这三个线程都执行完,再执行后续工作