对不起,我不知道如何用最简单的话来描述它,但基本上我想要做的是从方法返回一个LinkedList。但是我想将实际的内容放在一个线程内部的方法中,然后在线程完成时返回数据。以下是我正在使用的代码:从线程返回方法
public static LinkedList<Result> get(final String prefix){
final LinkedList<Result> results = new LinkedList<Result>();
if(thread != null){
thread.stop();
thread = null;
}
thread = new Thread(
new Runnable(){
public void run(){
try{
URL url = new URL(String.format(URL_INFO, prefix));
URLConnection connection = url.openConnection();
connection.setReadTimeout(Timeout.TIMEOUT);
connection.setConnectTimeout(Timeout.TIMEOUT);
InputStream is = connection.getInputStream();
Scanner reader = new Scanner(is);
while(reader.hasNextLine()){
String line = reader.nextLine();
if(line != null){
if(line.contains(String.format(WORDS_INFO, prefix))){
String[] s = line.split(String.format(PREFIX_INFO, prefix));
String[] s2 = s[1].split("\">");
if(s2.length > 0){
for(int i = 1; i < s2.length; i++){
String l = s2[i];
String[] split = l.split(FINAL_SPLIT);
results.add(new Result(prefix, split[0].trim()));
}
}
break;
}
}
}
reader.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
);
thread.start();
return results;
}
线程在变量部分内部是静态定义的。基本上这里的问题是它返回一个空的LinkedList,因为它不会等待线程完成。在返回LinkedList之前,如何等待线程完成?任何帮助将不胜感激。谢谢。
注意:这个问题与读取URL无关,问题是它返回一个空的LinkedList,因为线程还没有完成,我想知道如何等待线程完成之前返回一些东西
为什么你要把它放在一个单独的线程,如果你想等待它返回? – gobernador 2012-07-19 01:39:50
线程的要点是并行处理。如果第一个线程要等待第二个线程完成,那么没有必要启动第二个线程。不妨在第一个线程上完成这项工作。 – Wyzard 2012-07-19 01:43:07
['Thread.stop()'](http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#stop%28%29)已弃用。请参阅[为什么Thread.stop,Thread.suspend和Thread.resume已弃用?](http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html) – 2012-07-19 01:43:31