您的位置:首页 > 编程语言 > Java开发

关于java线程池的研究-Future与FutureTask

2013-12-13 16:03 330 查看


Future是一个接口,代表可以取消的任务,并可以获得任务的执行结果

主要方法

1、boolean java.util.concurrent.FutureTask.cancel(boolean mayInterruptIfRunning)

解释:

Attempts to cancel execution of this task.

This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason.

If successful, and this task has not started when cancel is called, this task should never run.

If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should beinterruptedin
an attempt to stop the task.

After this method returns, subsequent calls toisDone will always return true. Subsequent calls toisCancelled
will always return true
if this method returned true.

2、String java.util.concurrent.FutureTask.get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException

解释:

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

如果在指定的时间内没有获取到结果(任务还为完成),则抛出timeout exception ,而不是返回null

在任务执行完成后,可以多次调用取回相同的结果

3、String java.util.concurrent.FutureTask.get()throws InterruptedException, ExecutionException

解释:

Waits if necessary for the computation to complete, and then retrieves its result.

在任务执行完成后,可以多次调用取回相同的结果

4、boolean java.util.concurrent.FutureTask.isDone()

解释:

Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.

FutureTask 是基本的实现了Future和runnable接口

实现runnable接口,说明可以把FutureTask实例传入到Thread中,在一个新的线程中执行。

实现Future接口,说明可以从FutureTask中通过get取到任务的返回结果,也可以取消任务执行(通过interreput中断)

实例:

例一:

Callable<String> callable= new Callable<String>() {

@Override
public String call() throws Exception {
System.out.println("in call ");
Thread.sleep(10000);
String time="dd";
System.out.println("in end");
return time;
}
};

//	ExecutorService executorService = Executors.newFixedThreadPool(2);
//	Future<String> future=	executorService.submit(callable);
FutureTask<String> future= new FutureTask<String>(callable);
//task.run();
Thread thread=	new Thread(future);
thread.start();
try {

String temp=null;

for(int i=0;i<5;i++){
System.out.println("i="+i);
try {
System.out.println("begin get result is done:"+future.isDone());
temp = future.get(4,TimeUnit.SECONDS);
System.out.println("result:"+temp);
} catch (Exception e) {
//e.printStackTrace();
System.err.println(e.getLocalizedMessage());
}
}

future.get();

System.out.println("end get result");
//future.get(2, TimeUnit.SECONDS);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//	executorService.shutdown();


输出:

in call

i=0

begin get result is done:false

i=1

null

begin get result is done:false

null

i=2

begin get result is done:false

in end

result:dd

i=3

begin get result is done:true

result:dd

i=4

begin get result is done:true

result:dd

end get result

例二:

Callable<String> callable= new Callable<String>() {

@Override
public String call() throws Exception {
System.out.println("in call ");
Thread.sleep(10000);
String time="dd";
System.out.println("in end");
return time;
}
};
Runnable runnable = new Runnable() {

@Override
public void run() {
System.out.println("in call ");
try {
int temp=0;
int i=9/temp;
System.out.println(i);
Thread.sleep(10000);
String time="dd";
System.out.println("in end");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//	e.printStackTrace();
System.out.println("runnable cancelled");
throw new RuntimeException("ddd");
}

}
};

FutureTask<String> task= new FutureTask<String>(runnable,"result");
//task.run();
Thread thread=	new Thread(task);
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("uncaughtException");
}
});
thread.start();
System.out.println("the end");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("cancel task");
task.cancel(true);
System.out.println("cancel task over");

输出:

the end

in call

cancel task

cancel task over
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息