WEB开发网
开发学院软件开发Java 多线程设计模式 -- futrue --新特性 阅读

多线程设计模式 -- futrue --新特性

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示:请求数据线程 Java代码 publicclassRequestDataimplementsCallable<Data>{@OverridepublicDatacall(){//TODOAuto-generatedmethodstubint[]arr=newint[100];try{Thread.sleep

请求数据线程

Java代码

public class RequestData implements Callable<Data> { 
 
 @Override 
 public Data call() { 
 // TODO Auto-generated method stub 
 int[] arr = new int[100]; 
 try { 
  Thread.sleep(2000); 
 } catch (InterruptedException e) { 
  // TODO Auto-generated catch block 
  e.printStackTrace(); 
 } 
 for (int i = 0; i < 100; i++) { 
  arr[i] = i; 
 } 
 
 Data data = new Data(); 
 data.setDataArr(arr); 
 return data; 
 
 } 
 
}

数据

Java代码   

public class Data { 
 
 private int[] dataArr = new int[100]; 
 
 public int[] getDataArr() { 
 return dataArr; 
 } 
 
 public void setDataArr(int[] dataArr) { 
 this.dataArr = dataArr; 
 } 
}

测试类

Java代码

public class Main {  
  
  /** 
   * @param args 
   */  
  public static void main(String[] args) {  
    // TODO Auto-generated method stub  
  
    ExecutorService es = Executors.newFixedThreadPool(4);  
  
    RequestData r1 = new RequestData();  
    RequestData r2 = new RequestData();  
    RequestData r3 = new RequestData();  
    RequestData r4 = new RequestData();  
  
    System.out.println("Begin......");  
      
    Future f1 = es.submit(r1);  
    Future f2 = es.submit(r2);  
    Future f3 = es.submit(r3);  
    Future f4 = es.submit(r4);  
      
  
    Data data1 = null;  
    Data data2 = null;  
    Data data3 = null;  
    Data data4 = null;  
    try {  
      data1 = f1.get();  
      data2 = f2.get();  
      data3 = f3.get();  
      data4 = f4.get();  
    } catch (InterruptedException e) {  
      // TODO Auto-generated catch block  
      e.printStackTrace();  
    } catch (ExecutionException e) {  
      // TODO Auto-generated catch block  
      e.printStackTrace();  
    }  
  
    System.out.println(data1.getDataArr().length);  
    System.out.println(data2.getDataArr().length);  
    System.out.println(data3.getDataArr().length);  
    System.out.println(data4.getDataArr().length);  
      
    System.out.println("End......");  
      
      
  
    es.shutdown();  
  
  }  

Tags:线程 设计模式 futrue

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接