并发耗时计算模拟

  1. 云栖社区>
  2. 博客>
  3. 正文

并发耗时计算模拟

rrr1111 2015-03-10 11:12:00 浏览699
展开阅读全文
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureTaskDemo {
	public static void main(String[] args) {
		// 初始化一个Callable对象和FutureTask对象
		Callable pAccount = new PrivateAccount();
		FutureTask futureTask = new FutureTask(pAccount);
		
		// 使用futureTask创建一个线程
		Thread pAccountThread = new Thread(futureTask);
		System.out.println("futureTask线程现在开始启动,启动时间为:" + System.nanoTime());
		pAccountThread.start();
		System.out.println("主线程开始执行其他任务");
		// 从其他账户获取总金额
		int totalMoney = new Random().nextInt(100000);
		System.out.println("现在你在其他账户中的总金额为" + totalMoney);
		
		
		System.out.println("等待私有账户总金额统计完毕...");
		// 测试后台的计算线程是否完成,如果未完成则等待
		while (!futureTask.isDone()) {
			try {
				Thread.sleep(500);
				System.out.println("私有账户计算未完成继续等待...");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("futureTask线程计算完毕,此时时间为" + System.nanoTime());
		Integer privateAccountMoney = null;
		try {
			privateAccountMoney = (Integer) futureTask.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println("您现在的总金额为:" + totalMoney
				+ privateAccountMoney.intValue());
	}
}

@SuppressWarnings("all")
class PrivateAccount implements Callable {
	Integer totalMoney;

	public Object call() throws Exception {
		Thread.sleep(5000);
		totalMoney = new Integer(new Random().nextInt(10000));
		System.out.println("您当前有" + totalMoney + "在您的私有账户中");
		return totalMoney;
	}

}

网友评论

登录后评论
0/500
评论
rrr1111
+ 关注