-1

我正在开发一个多线程 Java 项目,我的一个线程正在联系一个网页。目前我这样做如下:

URLConnection urlConn = webPageToContact.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff  = new BufferedReader(inStream);

我的问题是,有没有办法以线程方式执行此操作,以便在该线程等待服务器响应时,我项目中的其他线程可以做事。我正在考虑某种“等待”方法。谢谢!

4

2 回答 2

3

您还可以使用单线程池执行器:

ExecutorService service = Executors.newSingleThreadExecutor();
   service.submit(new Runnable() {
   @Override public void run() {
      URLConnection urlConn = webPageToContact.openConnection();
      InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
      BufferedReader buff  = new BufferedReader(inStream);
      // put data in queue or some other data structure
   }    
});

service.shutdown();
于 2012-12-02T09:46:05.990 回答
1

尝试这个:

Thread webReader = new Thread(){
    public void run(){
        URLConnection urlConn = webPageToContact.openConnection();
        InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
        BufferedReader buff  = new BufferedReader(inStream);
    }
});
webReader.setDaemon(true);
webReader.start();
于 2012-12-02T09:34:28.593 回答