jdk5.0 多线程学习笔记(八)

    前面已经介绍过future模式和jdk5中的future,在jdk5中对future有个基本实现,这个实现就是类futuretask。

对于future模式,每个人都有自己的理解。这里引用他人的话,做个理解:

Future 模式就是在主线程中当需要进行比较耗时的作业,但不想阻塞主线程的作业时,将耗时作业交由 Future 对象在后台中完成,当主线程将来(这个 Future 的意义也就体现在这里了)需要时即可通过 Future 对象获得已经作业对象。”

 

下面举个例子,来加深理解,:)其实,看代码容易理解。

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class testFutureTask {
	public static void main(String[] args) {
		// Init callable object and future task
		Callable pAccount = new PrivateAccount();
		FutureTask futureTask = new FutureTask(pAccount);

		// Create a new thread to do so
		Thread pAccountThread = new Thread(futureTask);
//this will call the method call of PrivateAccount		
pAccountThread.start();

		// Do something else in the main thread
		System.out.println(" Doing something else here. ");

		// Get the total money from other accounts
		int totalMoney = new Random().nextInt(100000);
		System.out.println(" You have  " + totalMoney
				+ "  in your other Accounts. ");
		System.out.println(" Waiting for data from Private Account ");
		// If the Future task is not finished, we will wait for it
		while (!futureTask.isDone()) {
			try {
				Thread.sleep(5);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		Integer privataAccountMoney = null;
		// Since the future task is done, get the object back
		try {
			privataAccountMoney = (Integer) futureTask.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println(" The total moeny you have is  "
				+ (totalMoney + privataAccountMoney.intValue()));
	}

}

 

import java.util.Random;
import java.util.concurrent.Callable;

public class PrivateAccount implements Callable {
	Integer totalMoney;

	public Integer call() throws Exception {
		// Simulates a time conusimg task, sleep for 10s
		Thread.sleep(10000);
		totalMoney = new Integer(new Random().nextInt(10000));
		System.out.println(" You have  " + totalMoney
				+ "  in your private Account. ");
		return totalMoney;
	}

}

 

从上面的代码可以看出有了futuretask,利用future模式完成任务还是很方便的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值