将List Iterator传递给Java中的多个线程

Tom*_*ght 6 java multithreading iterator listiterator

我有一个包含大约200K元素的列表.

我能够将此列表的迭代器传递给多个线程并让它们遍历整个批次,而没有任何访问相同的元素吗?

这就是我现在想到的.

主要:

public static void main(String[] args)
{
    // Imagine this list has the 200,000 elements.
    ArrayList<Integer> list = new ArrayList<Integer>();

    // Get the iterator for the list.
    Iterator<Integer> i = list.iterator();

    // Create MyThread, passing in the iterator for the list.
    MyThread threadOne = new MyThread(i);
    MyThread threadTwo = new MyThread(i);
    MyThread threadThree = new MyThread(i);

    // Start the threads.
    threadOne.start();
    threadTwo.start();
    threadThree.start();
}
Run Code Online (Sandbox Code Playgroud)

MyThread的:

public class MyThread extends Thread
{

    Iterator<Integer> i;

    public MyThread(Iterator<Integer> i)
    {
        this.i = i;
    }

    public void run()
    {
        while (this.i.hasNext()) {
            Integer num = this.i.next();
            // Do something with num here.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我期望的结果是每个线程每个处理大约66,000个元素,而不会过多地锁定迭代器,并且没有任何线程访问相同的元素.

这听起来有用吗?

Arn*_*lle 7

您真的需要手动操作线程和迭代器吗?您可以使用 Java 8Stream并让其parallel()完成这项工作。

默认情况下,当您拥有处理器时,它将少使用一个线程。

例子 :

list.stream()
    .parallel()
    .forEach(this::doSomething)
;

//For example, display the current integer and the current thread number.
public void doSomething(Integer i) {
  System.out.println(String.format("%d, %d", i, Thread.currentThread().getId()));
}
Run Code Online (Sandbox Code Playgroud)

结果 :

49748, 13
49749, 13
49750, 13
192710, 14
105734, 17
105735, 17
105736, 17
[...]
Run Code Online (Sandbox Code Playgroud)

编辑:如果您使用的是 Maven,则需要添加这段配置pom.xml才能使用 Java 8:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.3</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
      </configuration>
    </plugin>
  </plugins>
</build>
Run Code Online (Sandbox Code Playgroud)