我正在开发一个多线程Java项目,我的一个线程正在联系一个网页。目前我这样做如下:
URLConnection urlConn = webPageToContact.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
我的问题是,有没有办法以线程方式执行此操作,以便在此线程等待服务器响应时,我的项目中的其他线程可以执行操作。我在考虑某种“等待”等等。方法。谢谢!
答案 0 :(得分: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();
答案 1 :(得分: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();