我怎么能做同步请求?

时间:2015-10-30 19:19:49

标签: java android multithreading

不明白如何在线程中发出同步请求,不要在另一个线程中阻止请求。我的代码:

for (Obj obj: objects) {
       Thread t = new Thread(new Runnable() {
       @Override
       public void run() {
       try {
          res = hDownloadUrl(obj.url, null); // always whait before get query from another thread
          newUrl = res.getUrl();
          res2 = hDownloadUrl(obj.url, null);
          //  ..............

       } catch (IOException e) {
         e.printStackTrace();
       }
       }
    });
    t.start();
}

其中hDownloadUrl:

   public InputStream hDownloadUrl(String urlString, String userAgent) throws IOException {
        Log.w("Helper hDownloadUrl: ", urlString);
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        if (userAgent != null){
            conn.setRequestProperty("User-Agent", userAgent);
        }
        conn.connect();
        return conn.getInputStream();
    }

0 个答案:

没有答案