简体   繁体   English

从Thread返回方法

[英]Return from method with Thread

Sorry for the confusing title, I'm not sure how to describe it in minimal words but basically what I'm trying to do is return a LinkedList from a method. 很抱歉这个令人困惑的标题,我不知道如何用最少的单词来描述它,但基本上我要做的是从方法返回一个LinkedList。 But I wanna put the actual content inside the method inside a Thread, and then return the data when the thread is done. 但我想将实际内容放在Thread内部的方法中,然后在线程完成时返回数据。 Here is the code I am using: 这是我正在使用的代码:

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

The thread is statically defined inside the variables section. 线程在变量部分内静态定义。 And basically the problem here is that it returns an empty LinkedList because it's not waiting for the Thread to be finished. 基本上这里的问题是它返回一个空的LinkedList,因为它不等待Thread完成。 How can I wait until the Thread is finished before returning the LinkedList? 在返回LinkedList之前,我怎么能等到Thread完成? Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks. 谢谢。

NOTE: The issue is not anything to do with reading the URL, the problem is is that it's returning an empty LinkedList because the Thread has not finished yet and I want to know how to wait until the Thread is done before it returns something. 注意:问题与读取URL没有任何关系,问题是它返回一个空的LinkedList,因为Thread尚未完成,我想知道如何等待Thread返回之前完成。

You need to wait till the thread completes execution. 您需要等到线程完成执行。 Look up the documentation on Thread.join . 查看Thread.join上的文档。

This is just one way to do what you are trying. 这只是一种做你正在尝试的方法。 There are many others, such as ExecutorService 还有很多其他的,例如ExecutorService

I'm not sure why you are using a thread here at all. 我不知道你为什么要在这里使用一个帖子。 If you have to fork the thread and then wait for it to finish, then you should just execute the run() code directly in the parent thread. 如果你必须分叉线程然后等待它完成,那么你应该直接在父线程中执行run()代码。

It is also important to realize that when you do something like: 同样重要的是要意识到当你做以下事情时:

final LinkedList<Result> results = new LinkedList<Result>();
thread = new Thread(
        new Runnable(){
            public void run(){
                ...
                results.add(new Result(prefix, split[0].trim()));
...
return results;

You are using the results object in a non-thread-safe manner. 您正在以非线程安全的方式使用results对象。 results is not a synchronized collection so you would need to synchronize on it both in the Runnable and in the outer thread if you actually wanted to return it while the thread was still running. results不是同步集合,因此如果您确实想在线程仍在运行时返回它,则需要在Runnable和外部线程中同步它。 Otherwise two threads are accessing the object without memory synchronization. 否则两个线程正在访问该对象而没有内存同步。 Since you may now be calling join() on the thread before returning, this would be a non issue since join() will synchronize for you. 由于您现在可能返回之前在线程上调用join() ,这将是一个非问题,因为join()将为您进行同步。 But it is important to realize the ramifications there. 但重要的是要认识到那里的后果。

Lastly, thread.stop() is deprecated. 最后,不推荐使用thread.stop() The right way to interrupt a thread is to call thread.interrupt() which sets the interrupt flag on the thread and causes Thread.sleep() , wait() , and some other methods to throw InterruptedException . 中断线程的正确方法是调用thread.interrupt() ,它在线程上设置中断标志并导致Thread.sleep()wait()和其他一些方法抛出InterruptedException

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

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