FutureTask的简单用法
package com.fmp.orderManager.util;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.fmp.orderManager.pojo.OrderManager;
import com.fmp.util.Public;
public class FutureTest {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
/*实体类*/
final OrderManager ord1 = new OrderManager();
ord1.setOrderNo("11111");
ord1.setCreatTime(Public.DateTOString(new Date())); /**时间*/
FutureTask<OrderManager> future = new FutureTask<OrderManager>(
new Callable<OrderManager>() {
@Override
public OrderManager call() throws Exception {
// TODO Auto-generated method stub
Thread.sleep(30*1000);
System.out.println("---------沉睡中------------");
System.out.println(ord1.getCreatTime());
return ord1;
}
});
executor.execute(future);
System.out.println("future==" + future);
try {
OrderManager result = future.get(30*1000, TimeUnit.MILLISECONDS);
System.out.println(Public.DateTOString(new Date()));
System.out.println("result==" + result.getOrderNo());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
future.cancel(true);
executor.shutdown();
}
}
}