简体   繁体   English

Java-线程中的URL连接

[英]Java - URL Connection in Threads

I currently have a project where different parameters are requested from an online CGI file, and each request is supposed to be processed in different threads. 我目前有一个项目,其中从在线CGI文件请求不同的参数,并且每个请求都应该在不同的线程中进行处理。 When I run my code by itself it works great, however it doesn't seem to connect when I put it in a thread. 当我自己运行代码时,它可以很好地运行,但是当我将其放入线程中时,似乎没有连接。 My code is below: 我的代码如下:

public void run() {
    connect();
}


public synchronized void connect(){
    StringBuffer response = new StringBuffer("");
    try {

        String data = "year=" + year + "&top=" + numNames + "number=";
        // Send data
        URL url = new URL("http://www.ssa.gov/cgi-bin/popularnames.cgi");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;

        while ((line = rd.readLine()) != null) {
            response.append(line);
        }
        wr.close();
        rd.close();
    } catch (Exception e) {
        System.out.println(e);
    }
System.out.println(response);
        }
    }

Remove the synchronized call on connect. 删除连接上的同步呼叫。 That should solve your problem 那应该解决你的问题

public synchronized void connect(){ 公共 同步 void connect(){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM