import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableAndFuture
{
public static void main(String[] args)
{
/*
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<String> future = threadPool.submit(new Callable<String>(){
public String call() throws Exception
{
Thread.sleep(2000);
return "hello";
};
});
System.out.println("等待结果");
try
{
System.out.println("拿到结果:" + future.get());
}
catch (Exception e)
{
e.printStackTrace();
}
*/
//固定大小线程池
ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
final CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
final int t = 1000;
final Random r = new Random();
//任务生产线程
new Thread( new Runnable(){
@Override
public void run()
{
while (true)
{
System.gc();
try
{
//控制任务生产线程的生产速度,以避免生产速度过快,new的Callable任务对象过多,导致java.lang.OutOfMemoryError
Thread.sleep(10000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
for(int j = 0;j < 100;j++)
{
//注意:这里有可能抛出java.lang.OutOfMemoryError,应适当予以捕获
completionService.submit(new Callable<Integer>(){
@Override
public Integer call() throws Exception
{
Thread.sleep(t);
return r.nextInt(50000);
}
});
}
}
}
}
).start();
//主线程获取任务的处理结果
while (true)
{
try
{
Future<Integer> f = completionService.take();
System.out.println(f.get());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}