java多线程返回函数结果

来源:互联网 发布:net.sf.json官方下载 编辑:程序博客网 时间:2024/06/14 04:39

两种方式:一种继承Thread类实现;一种通过实现Callable接口。

第一种方法:

因为实现Thread类的run方法自身是没有返回值的,所以不能直接获得线程的执行结果,但是可以通过在run方法里把最后的结果传递给实例变量,然后通过getXX方法获取该实例变量的值。继承实现的代码:

[java] view plaincopy
  1. class RunThread extends Thread{    
  2.     private String runLog;  
  3.     private BufferedReader br;  
  4.     {  
  5.         runLog = "";  
  6.     }  
  7.     public RunThread(BufferedReader br){  
  8.         this.br = br;  
  9.     }  
  10.     public void run() {  
  11.         try {    
  12.             String output = "";  
  13.             while ((output = br.readLine()) != null) {    
  14.                 this.runLog += output + "\n";    
  15.             }      
  16.         } catch (IOException e) {  
  17.             e.printStackTrace();  
  18.         }   
  19.     }     
  20.     public String getRunLog(){  
  21.         return this.runLog;  
  22.     }  
  23. }   

第二种方法:

继承Callable接口后需要实现call方法,而call方法默认是可以有返回值的,所以可以直接返回想返回的内容。接口的实现代码:

[java] view plaincopy
  1. class CallThread implements Callable<String>{    
  2.     private String runLog;  
  3.     private BufferedReader br;  
  4.     {  
  5.         runLog = "";  
  6.     }  
  7.     public CallThread(BufferedReader br){  
  8.         this.br = br;  
  9.     }  
  10.     @Override  
  11.     public String call() throws Exception {  
  12.         try {    
  13.             String output = "";  
  14.             while ((output = br.readLine()) != null) {    
  15.                 runLog += output + "\n";    
  16.             }                
  17.         } catch (IOException e) {              
  18.             return runLog;              
  19.         }   
  20.         return runLog;  
  21.     }       
  22. }    

下面就来调用了。

第一种方式的调用代码:

[java] view plaincopy
  1. RunThread th1 = new RunThread(standout);  
  2. th1.start();                                  
  3. RunThread th2 = new RunThread(standerr);  
  4. th2.start();  
  5. th2.join();    //保障前面2个线程在主进程之前结束,否则获取的结果可能为空或不完整                               
  6. runLog += th1.getRunLog() + "\n";  
  7. runLog += th2.getRunLog() + "\n";   

第二种方式的调用代码:

[java] view plaincopy
  1. ExecutorService exs = Executors.newCachedThreadPool();    
  2.    ArrayList<Future<String>> al = new ArrayList<Future<String>>();     
  3.    al.add(exs.submit(new CallThread(standout)));    
  4.    al.add(exs.submit(new CallThread(standerr)));              
  5.    for(Future<String> fs:al){    
  6.        try {    
  7.         runLog += fs.get() + "\n";    
  8.        } catch (InterruptedException e) {    
  9.            e.printStackTrace();    
  10.        } catch (ExecutionException e) {    
  11.            e.printStackTrace();    
  12.        }    
  13.    }    
转载自:http://blog.csdn.net/five3/article/details/11592889
0 0