我怎么能把它变成一个线程,所以它不冻结我的应用程序?

时间:2015-11-22 05:44:11

标签: multithreading thread-safety

所以我想知道如何把它变成一个线程?我多次尝试过失败。我正准备放弃,只是在收到回复时处理冻结应用程序。

package me.robert.tb.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class HTTPConnect {

private static BufferedReader reader = null;
private static StringBuilder buffer = new StringBuilder();

/**
 * This method is used to connect to a website and return its response.
 * Mainly used for connecting to API's
 *
 * @param link
 *            The URL of the website
 * @return The response from the website
 */
public static String getResponse(String link) {
try {
    reader = new BufferedReader(new InputStreamReader(new      URL(link).openStream()));

    int read;
    char[] chars = new char[1024];
    while ((read = reader.read(chars)) != -1)
    buffer.append(chars, 0, read);
} catch (Exception e) {
} finally {
    try {
    if (reader != null)
        reader.close();
    } catch (IOException e) {
    }
}
return buffer.toString();
}
}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

你走了。虽然你不应该真的需要线程来导入1024个字符。在几个测试页面上,它运行得非常快。我认为你的主要问题是试图让getResponse()保持静态。无论如何,这是使用线程修改的代码。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class HTTPConnect implements Runnable{

    private static BufferedReader reader = null;
    private static StringBuilder buffer = new StringBuilder();
    private String link;
    private String response;

    /**
     * This method is used to connect to a website and return its response.
     * Mainly used for connecting to API's
     *
     * @param link
     *            The URL of the website
     * @return The response from the website
     */
    public HTTPConnect(String input){
        link = input;
    }
    public void run() {
        try {
            reader = new BufferedReader(new InputStreamReader(new URL(link).openStream()));

            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read);
        } catch (Exception e) {
        } finally {
            try {
                if (reader != null)
                    reader.close();
                response = buffer.toString();
            } catch (IOException e) {
            }
        }
    }

    public String getResponse(){
        return response;
    }

    public static void main (String[] args){
        String website = "http://google.com";
        Thread t = new Thread(new HTTPConnect(website));
        t.run();
    }
}