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 ;
          }
    

      


  • 相关阅读:
    UVW源码漫谈(四)
    UVW源码漫谈(三)
    UVW源码漫谈(番外篇)—— Emitter
    UVW源码漫谈(一)
    UVW源码漫谈(二)
    如何利用GDI图像来制作验证码(在winform上面制作的当然也可以在web上面制作)
    利用C语言版本的数据库制作一个学生成绩管理系统
    行内元素与块级元素的区别
    filter的两种使用方法
    JavaScript随机数类型
  • 原文地址:https://www.cnblogs.com/LCX/p/4509628.html
Copyright © 2011-2022 走看看