thread.join 从异步执行变成同步

  •    Java的线程模型为我们提供了更好的解决方案,这就是join方法。在前面已经讨论过,join的功能就是使用线程 从异步执行变成同步执行
  •   当线程变成同步执行后,就和从普通的方法中得到返回数据没有什么区别了。因此,可以使用如下的代码更有效地解决这个问题:
  •   
  • Java代码       
  • thread.start();    
  • thread.join();    
  • ...    
  •  在thread.join()执行完后,线程thread的run方法已经退出了,也就是说线程thread已经结束了。因此,在thread.join()后面可以放心大胆地使用MyThread类的任何资源来得到返回数据。   

public static String getAddress (final InputStream inputStream, final String mobile) {
            Thread thread = new Thread() {
                   public void run() {
                         try {
                              Log. i(TAG, "inputStream: " + inputStream.available());
                              String soap = readSoapFile(inputStream, mobile);
                               byte[] data = soap.getBytes();

                              URL url = new URL(
                                           "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx" );
                              HttpURLConnection conn = (HttpURLConnection) url
                                          .openConnection();
                              conn.setDoOutput( true);
                              conn.setConnectTimeout(5 * 1000);
                              conn.setRequestMethod( "POST");
                              conn.setRequestProperty( "Content-Type",
                                           "application/soap+xml; charset=utf-8");
                              conn.setRequestProperty( "Content-Length",
                                          String. valueOf(data.length)); 

                              OutputStream outputStream = conn.getOutputStream();
                              outputStream.write(data);
                              outputStream.flush();
                              outputStream.close();
                              
                               if (conn.getResponseCode() == 200) {
                                     address =parseResponseXML(conn
                                                .getInputStream()); 
                              }
                        } catch (Exception e) {
                        }
                  };
            };
            thread.start();
             try { thread.join(); } catch (Exception e) {}
             if(address !=null){
                   return address ;
            }
             return null ;
      }

  


posted @ 2015-05-17 14:12  大力  阅读(828)  评论(0编辑  收藏  举报