Future结合ExecutorService的简单实例

Future结合ExecutorService的简单实例

//ValueObject类

public   class  AdEntity {
    
private  String id;
    
private  String name;
    
private  String broker;
    
private  String date;
    
private  String body;
    
// get/set
    
    
public  String toString(){
        
return   " 【编号为: " + id + " ,广告名称为: " + name + " ,代理商为: " + broker + " ,发布日期为: " + date + " ,内容为: " + body + " " ;
    }
}

//调用任务类

public   class  AdTask  implements  Callable < AdEntity >  {
    @Override
    
public  AdEntity call()  throws  Exception {
        
//  模拟远程调用花费的一些时间
        Thread.sleep( 5 * 1000 );
        AdEntity vo
= new  AdEntity();
        vo.setId(String.valueOf(
new  Random().nextInt( 1000 )));
        vo.setName(
" Ad@内衣广告 " );
        vo.setBroker(
" CHANNEL " );
        Date date
= new  Date();
        SimpleDateFormat sdf
= new  SimpleDateFormat( " yyyy-MM-dd " );
        String dateStr
= sdf.format(date);
        vo.setDate(dateStr);
        vo.setBody(
" 远端内容 " );
        
return  vo;
    }
}

//主函数

public   class  TestQueryMemg {
    
    
/**
     * 
@param  args
     * 
@throws  ExecutionException 
     * 
@throws  InterruptedException 
     
*/
    
public   static   void  main(String[] args)  throws  InterruptedException, ExecutionException {
        ExecutorService exec
= Executors.newCachedThreadPool();
        
// 创建Future来完成网络调用任务
        Callable < AdEntity >  returnAd = new  AdTask();
        Future
< AdEntity >  future = exec.submit(returnAd);
        
        
// 开始执行本地化查询信息
        AdEntity localAd = new  AdEntity();
        localAd.setId(String.valueOf(
new  Random().nextInt( 1000 )));
        localAd.setName(
" Ad@食品广告 " );
        localAd.setBroker(
" 蒙牛 " );
        SimpleDateFormat sdf
= new  SimpleDateFormat( " yyyy-MM-dd " );
        String dateStr
= sdf.format( new  Date());
        localAd.setDate(dateStr);
        localAd.setBody(
" 内容本地 " );

        System.out.println(
" 当前本地化查询内容为: " + localAd.toString());
        System.out.println(
" 稍等片刻以获取远端信息 " );
        
        
while ( ! future.isDone()){
            
try  {
                Thread.sleep(
1 * 1000 );
            } 
catch  (InterruptedException e) {
                e.printStackTrace();
            }
        }
        AdEntity entityRemote
= (AdEntity)future.get();

        System.out.println(
" 合并查询内容为:\n " + localAd.toString() + " \n " + entityRemote.toString());
    }
}


 

 

 

你可能感兴趣的:(Future结合ExecutorService的简单实例)