Java中的多线程处理

时间:2012-05-09 07:58:40

标签: java multithreading

我只是遇到一些问题让我解决这个问题。任何帮助将不胜感激。

程序必须读取一个文本文件,它将计算每个输入数字的除数之和。例如,数字20的总和为1 + 2 + 4 + 5 + 10 = 22。然后将这些总和逐行求和。对于上面这些总和中的每一个,然后找到除数,然后最终将它们合计。

E.g初始文件 1 2 4 6 15 20

25 50 100 125 250 500

16 8 3

然后计算除数之和。

1 1 3 6 9 22

6 43 117 31 218 592

15 7 1

逐行总结

42

1007

23

然后计算上面的总和。

54

73

1

然后最终总结并返回。

128

我需要完成这个过程,每个新行由一个线程池完成。

我的逻辑如下。

              5.2. For each input line (Add each line to an ArrayBlockingQueue, 
Then add each item in the Queue to an ExecutorService Which will run the follow)   

               5.2.1. Parse the current input line into integers 

               5.2.2. For each integer in the current input line 

                   5.2.2.1. Compute the sum-of-divisors of this integer 

                   5.2.2.2. Add this to the cumulated sum-of-divisors 

               5.2.3. Compute the sum-of-divisors of this cumulated sum

               5.2.4. Add this to the grand total

我在5.2之后陷入困境,我是创建一个实现runnable接口的新类,然后将累积的和添加到atomicArray,或者最好创建一个实现可调用接口的类,然后让它返回累计金额?或者有一种完全不同的方式。

这是我到目前为止所返回的所需结果,但是是顺序的。

http://pastebin.com/AyB58fpr

2 个答案:

答案 0 :(得分:1)

使用

java.util.concurrent.Future

java.util.concurrent.Executors.newFixedThreadPool(int nThreads)

这很容易做到。

如果您不熟悉执行者,请关注Oracle tutorial

答案 1 :(得分:1)

我更喜欢Callable接口,因为这不会创建代码的依赖关系,该代码将输入处理为如何收集输出。

通常的方法是在Future列表中收集任务。 See this answer举个例子。