码迷,mamicode.com
首页 > 编程语言 > 详细

java的Future用法

时间:2014-10-18 14:06:15      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   java   2014   on   log   ad   

首先,Future是一个接口,该接口用来返回异步的结果。

package com.itbuluoge.mythread;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

class TaskWithResult implements Callable<String>
{

	public String call() throws Exception {
		// TODO Auto-generated method stub
		Thread.sleep(1000);
		return "OK";
	}
	
}
public class CallableDemo {

	/**
	 * @param args
	 * @throws Exception 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException, Exception {
		// TODO Auto-generated method stub
		ExecutorService exec=Executors.newCachedThreadPool();
		Future<String> st=exec.submit(new TaskWithResult());
		
		/*同步结果,并且设置超时时间*/
		System.out.println(st.get(10000, TimeUnit.MILLISECONDS));
		System.out.println("over");
		
		
	}

}


其中st.get(10000, TimeUnit.MILLISECONDS)是同步阻塞的,也就是说,会一直等待st的返回结果,在结果返回后,才会继续执行下去。

输出结果

bubuko.com,布布扣
bubuko.com,布布扣

java的Future用法

标签:blog   http   io   ar   java   2014   on   log   ad   

原文地址:http://blog.csdn.net/itbuluoge/article/details/40210695

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!