01 FutureTask的基本特征
- 泛型定义
- 构造函数传入一个callable
- 实现了runnable接口
- 有get方法,返回callable执行结果,并且有阻塞效果。
02 代码实现
import java.util.concurrent.Callable;
import org.apache.poi.ss.formula.functions.T;
public class MyFutureTask<T> implements Runnable
{
private String state = "START";
private Callable<T> callable;
private T result;
public MyFutureTask(Callable callable)
{
this.callable = callable;
}
public void run()
{
try
{
result = callable.call();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
state = "END";
}
synchronized (this)
{
this.notify();
}
}
public T get()
{
if ("END".equals(state))
{
return result;
}
synchronized (this)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
return result;
}
}
03 测试下
import java.util.concurrent.Callable;
public class Test
{
public static void main(String[] args)
{
Callable<Object> callable1 = new Callable<Object>()
{
public Object call() throws Exception
{
Thread.currentThread().sleep(3000);
return "hello";
}
};
Callable<Object> callable2 = new Callable<Object>()
{
public Object call() throws Exception
{
Thread.currentThread().sleep(5000);
return "world";
}
};
MyFutureTask task1 = new MyFutureTask(callable1);
MyFutureTask task2 = new MyFutureTask(callable2);
new Thread(task1).start();
new Thread(task2).start();
System.out.println(task1.get());
System.out.println(task2.get());
}
}