Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
线程中的Java-URL连接_Java_Multithreading_Url_Connection - Fatal编程技术网

线程中的Java-URL连接

线程中的Java-URL连接,java,multithreading,url,connection,Java,Multithreading,Url,Connection,我目前有一个项目,从一个在线CGI文件中请求不同的参数,每个请求都应该在不同的线程中处理。当我自己运行代码时,它工作得很好,但是当我把它放在线程中时,它似乎没有连接。 我的代码如下: public void run() { connect(); } public synchronized void connect(){ StringBuffer response = new StringBuffer(""); try { String data =

我目前有一个项目,从一个在线CGI文件中请求不同的参数,每个请求都应该在不同的线程中处理。当我自己运行代码时,它工作得很好,但是当我把它放在线程中时,它似乎没有连接。 我的代码如下:

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

删除connect上的同步调用。那应该能解决你的问题


公共同步的void connect(){

如果
connect
方法属于一个被多个线程使用的对象实例,一次只能运行一个,但我怀疑这不是您想要问的。哦,如果
connect
没有改变自身以外的任何内容,那么它可能没有理由被
同步。