我在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次任务,直到需要时才运行。
一些其他注意事项:
最佳答案
我认为在您的情况下,您只能使用在任务之间共享的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);
}
}