FutureTask 实例

先来总结一下FutureTask使用场景:

如果不想分支线程阻塞主线程,又想取得分支线程的执行结果,就用FutureTask。可用于提交加载稍后需要的数据,或是复杂的计算。

代码如下:

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class FutureTaskTest {

	private FutureTask<String> futureTask  = new FutureTask<String>(new SayHelloCallable());
	
	private void sayHello() throws Exception{
		futureTask.run();
		String content = futureTask.get();
		System.out.println(content);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
			FutureTaskTest test = new FutureTaskTest();
			test.sayHello();
	}
}

class SayHelloCallable implements Callable<String> {

	@Override
	public String call() throws Exception {
		TimeUnit.SECONDS.sleep(2L);
		return "Hello";
	}
}

 

你可能感兴趣的:(FutureTask)