我在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);
      }
    }
    

    10-05 21:12
    查看更多