如何使用执行器框架在Java中使用线程添加数字?

时间:2018-04-01 15:37:54

标签: java multithreading executorservice

我想知道我可以使用多线程添加10个数字,但要考虑的要点如下:

  1. 我想将(1,2)(3,4)(5,6)等数字分组,并在单独的线程中执行添加。
  2. 使用执行器future.get方法获取结果并再次对结果进行分组,例如(1,2)给出3和(3,4)给出7所以现在我想把这两个结果分组并传递给另一个线程进行加法(3,7)
  3. 重复相同的过程,直到得到结果的单个数字。
  4. 我已经过了一半,但不知道如何继续前进,我也不确定是否可以分组和添加结果的剩余部分。

    public class CallableAdder implements Callable<Integer> {
    
    Integer operand1;
    Integer operand2;
    CallableAdder(Integer operand1,Integer operand2)
    {
        this.operand1=operand1;
        this.operand2=operand2;
    
    }
    
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName()+" says : partial Sum for " + operand1 + " and "+ operand2+ " is "  +(operand1+operand2));
        return operand1+operand2;
    }
    
    }
    

    另一堂课:

    public class ParallelAdder {
    public Integer parallelSum()
    {
        ExecutorService executor = Executors.newFixedThreadPool(10);
        List <Future<Integer>> list = new ArrayList<Future<Integer>>();
        int prev=0;
        for(int i=1;i<=10;i++)
        {
            if(i%2==0)         //grouping
            {
                System.out.println("Prev :" + prev + " current: " + i);
                Future<Integer> future = executor.submit(new CallableAdder(prev,i));
                list.add(future);
                continue;
            }
            prev=i;
        }
        int totsum=0;
        for(Future<Integer> fut : list)
        {
            try {
                totsum = totsum+ fut.get();  
       //This contains result from first iteration here I have added everything 
       //but what I wanted to do is create another thread and perform the same 
       //operation as I did before group and then add meaning repeating step 1 and 2
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        executor.shutdown();
        System.out.println("Total Sum is " + totsum);
        return totsum;   
    }
    
    public int sequentialSum()
    {
    
        Integer totsum=0;
        for(int i=0;i<=1000;i++)
        {
            totsum=totsum+i;
        }
        System.out.println("sequentialSum Total Sum is " + totsum);
        return totsum;
    }
    
    public static void main(String[] args) {
    
        ParallelAdder adder = new ParallelAdder();
        int pSum= adder.parallelSum();
        int sSum= adder.sequentialSum();
    
        System.out.println("parallel Sum equals to Sequential Sum ? " );
        System.out.println("Answer is :: "  + (pSum==sSum));
    
    }
    }
    

    请查看并帮我解决更多代码。

0 个答案:

没有答案