首页 > 代码库 > 业务代码中(java class)中如何实现多线程,并且将子线程中的值随方法返回返回值
业务代码中(java class)中如何实现多线程,并且将子线程中的值随方法返回返回值
转载自http://bbs.csdn.net/topics/390731832
问题:
public static String getAddress(final InputStream inputStream, final String mobile) { new Thread() { public void run() { try { Log.i(TAG, "inputStream: " + inputStream.available()); String soap = readSoapFile(inputStream, mobile); byte[] data =http://www.mamicode.com/ 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); // 设置超时时间为5秒 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()); // 解析服务器端返回的数据 } System.out.println("address=="+address);//这里是有值 } } catch (Exception e) { Log.e(TAG, e.toString()); System.out.println("获取手机号码归属地失败"); } }; }.start(); System.out.println("addres"+address);//这里返回的是空 return address; }
addess返回空值
因为不在一个线程中,所以值无法跨线程传递,解决方法:
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 =http://www.mamicode.com/ 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 ; }
业务代码中(java class)中如何实现多线程,并且将子线程中的值随方法返回返回值
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。