首先,我想说的是我正在从python到更复杂的代码。我现在正在学习Java,而且我是一个非常新的人。我了解Java确实擅长于多线程,因为我正在使用它来处理TB级的数据。

数据输入只是输入到迭代器中,我有一个类封装了一个运行函数,该函数从迭代器中提取一行,进行一些分析,然后将分析结果写入文件。线程之间必须共享的唯一信息是它们正在写入的对象的名称。简单吧?我只希望每个线程同时执行运行功能,以便我们可以快速遍历输入数据。在python中,这很简单。

from multiprocessing import Pool
f = open('someoutput.csv','w');
def run(x):
f.write(analyze(x))

p = Pool(8);
p.map(run,iterator_of_input_data);


因此,在Java中,我有1万行分析代码,并且可以很容易地遍历输入,并将其传递给运行函数,然后依次调用我所有的分析代码,并将其发送到输出对象。

public class cool {
    ...
    public static void run(Input input,output) {
        Analysis an = new Analysis(input,output);
    }
    public static void main(String args[]) throws Exception {
        Iterator iterator = new Parser(File(input_file)).iterator();
        File output = File(output_object);
        while(iterator.hasNext(){
            cool.run(iterator.next(),output);
        }
    }
}


我要做的就是让多个线程带有迭代器对象并执行run语句。一切都是独立的。我一直在看Java多线程的东西,但是它是用于通过网络交谈,共享数据等。这是否像我想的那样简单?如果有人可以将我指向正确的方向,我将很乐意做腿部工作。

谢谢

最佳答案

ExecutorService(ThreadPoolExecutor)将与Java等价。

ExecutorService executorService =
    new ThreadPoolExecutor(
        maxThreads, // core thread pool size
        maxThreads, // maximum thread pool size
        1, // time to wait before resizing pool
        TimeUnit.MINUTES,
        new ArrayBlockingQueue<Runnable>(maxThreads, true),
        new ThreadPoolExecutor.CallerRunsPolicy());

ConcurrentLinkedQueue<ResultObject> resultQueue;

while (iterator.hasNext()) {
    executorService.execute(new MyJob(iterator.next(), resultQueue))
}


将您的工作实现为Runnable。

class MyJob implements Runnable {
    /* collect useful parameters in the constructor */
    public MyJob(...) {
        /* omitted */
    }

    public void run() {
        /* job here, submit result to resultQueue */
    }
}


存在resultQueue来收集作业的结果。

有关详细信息,请参见java api documentation

07-25 23:40
查看更多