zoukankan      html  css  js  c++  java
  • 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 ;
          }
    

      


  • 相关阅读:
    一步一步学习Unity3d学习笔记系1.2 单机游戏和网游的数据验证概念
    一步一步学习Unity3d学习笔记系1.1
    Mongodb 官网驱动2.2.4.26版本 增,删 改,查
    使用Zxing 一维码
    Linq 数据排序,分页
    easyui datagrid 批量编辑和提交数据
    Json序列化为对象方法
    百度地图车辆运动轨迹
    GridView后台绑定数据列表方法
    删除重复数据
  • 原文地址:https://www.cnblogs.com/LCX/p/4509628.html
Copyright © 2011-2022 走看看