java - 使用 Java 并发运行多线程任务,直到有足够的输出

标签 java multithreading concurrency threadpool executor

我有一个 Java 任务,目前是单线程的,可能会也可能不会产生输出。我需要运行此任务,直到从中获得 100 条输出。这是单线程(大大简化)的示例版本:

import java.security.SecureRandom;

public class Test {

    private static SecureRandom rand = new SecureRandom();

    public static String task() {
        return rand.nextDouble() > 0.5 ? "output" : null;
    }

    public static void main(String[] args) {
        int outputCount = 0;
        while (outputCount < 100) {
            String output = task();
            if (output != null) {
                outputCount++;
                System.out.println(output);
            }
        }
    }
}

我想在四 (4) 个线程中以多线程方式运行此任务。我该如何实现?

我研究过使用 Executor interfaces但它们似乎适合将任务恰好运行 n 次,直到需要时才运行。

一些补充说明:

  • 我不在乎我是否得到 103 个输出并且不得不丢弃其中的 3 个
  • 任务使用的一个对象构造起来很昂贵,不是线程安全的,但可以被稍后运行的任务再次使用。 (这在上面的示例中由 SecureRandom 表示。)理想情况下,我想要一个线程池,它可以让我恰好实例化其中的四个对象。

最佳答案

我认为在你的情况下你可以只使用 AtomicInteger在您的任务之间共享。

public class MyTask
  implements Runnable
{
  private AtomicInteger counter;

  public MyTask ( AtomicInteger counter )
  {
    this.counter = counter;
  }

  public void run ()
  {
    while ( true )
    {
      String output = task();
      if ( output != null )
      {
        int count = counter.getAndIncrement( );

        System.out.println(output);
        if ( count >= 100 )
        {
          break;
        }
      }
    }
  }

  public static String task() {
    return rand.nextDouble() > 0.5 ? "output" : null;
  }

  public static void main (
      String[] args
    ) throws InterruptedException
  {
    AtomicInteger counter = new AtomicInteger( );

    ExecutorService pool = Executors.newFixedThreadPool(4);

    for (int i = 0; i < 4; ++i)
    {
        pool.execute( new MyTask( counter ) );
    }

    // Simplified shutdown, do not use this in production
    pool.shutdown( );
    pool.awaitTermination(1, TimeUnit.HOURS);
  }
}

关于java - 使用 Java 并发运行多线程任务,直到有足够的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25922372/

相关文章:

java - 如何使站点数据库的报告部分独立

java - 将对象从 Activity 传递到 IntentService

c++ - 使用 std::async 控制并行度

java - 当多个线程同时请求加载同一个类时会发生什么?

java - 处理超时的 FutureTask

java - 如何测量使用Sockets和并发时的时间

java - 设置网格宽度时在 JDialog w/GridBagLayout 中重叠

java - 线程停止、挂起和恢复

java - 无法使用 Thread.start() 启动 JavaFX 任务

python - python 2.7下xmlrpclib.ServerProxy的多线程问题