java - 将列表迭代器传递给 Java 中的多个线程

标签 java multithreading iterator listiterator

我有一个包含大约 20 万个元素的列表。

我是否可以将此列表的迭代器传递给多个线程并让它们遍历整个批处理,而不需要它们中的任何一个访问相同的元素?

这就是我此刻的想法。

主要内容:

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();
}

我的线程:

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.
        }
    }
}

我在这里期望的结果是每个线程将处理大约 66,000 个元素,而不会过多地锁定迭代器,也不会有任何线程访问同一元素。

这听起来可行吗?

最佳答案

真的需要手动操作线程和迭代器吗?您可以使用 Java 8 Stream 并让 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()));
}

结果:

49748, 13
49749, 13
49750, 13
192710, 14
105734, 17
105735, 17
105736, 17
[...]

编辑:如果您使用的是 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>

关于java - 将列表迭代器传递给 Java 中的多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35222548/

相关文章:

java - 未调用TargetDataLine的自定义实现方法

java - 专用 MySql 服务器与应用程序引擎配合使用

Android:onCreate() 被多次调用(不是我调用的)

C++推导的迭代器大小

c++ - 迭代器在指向整数时自动取消引用

java - Android 下载文件获取 FileNotFoundException

Java HashMap.get(key) 和 TreeMap.get(key) equals 和compareTo 方法的用法

java - 帮助 java 线程和执行器 : Executing several MySQL selects, 同时插入和更新

c# - 从线程中获取线程 ID

c++ - std::list 迭代器没有被分配