将列表迭代器传递给Java中的多个线程 [英] Passing a List Iterator to multiple Threads in Java

查看:53
本文介绍了将列表迭代器传递给Java中的多个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list that contains roughly 200K elements.

我是否可以将该列表的迭代器传递给多个线程,并让它们在整个线程中进行迭代,而又没有一个访问相同的元素?

Am I able to pass the iterator for this list to multiple threads and have them iterate over the whole lot, without any of them accessing the same elements?

这就是我目前所想的.

主要:

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

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

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

My desired outcome here is that each thread would process roughly 66,000 elements each, without locking up the iterator too much, and also without any of the threads accessing the same element.

这听起来可行吗?

推荐答案

您真的需要手动操作线程和迭代器吗?您可以使用Java 8 Stream s,然后让parallel()来完成这项工作.

Do you really need to manipulate threads and iterators manually? You could use Java 8 Streams and let parallel() do the job.

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

By default, it will use one less thread as you have processors.

示例:

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:

Edit : if you are using maven, you will need to add this piece of configuration in pom.xml in order to use 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中的多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆