CallableAndFuture

本文通过一个具体的Java示例,展示了如何使用Callable接口和Future对象来处理异步任务,并结合CompletionService来管理多个并发任务的执行结果。此外,还提供了一个包含任务生产和消费的简单线程模型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值