简体   繁体   English

执行Thread.join()之后,以相同的方法执行代码

[英]Execute code in the same method after Thread.join() executes

I have the problem, that the join Method, to kill a thread, is not executing the rest of the method, which was started also in the thread. 我有一个问题,就是杀死线程的join方法没有执行该方法的其余部分,该方法也是在线程中启动的。 Here is a code example: 这是一个代码示例:

private static Thread thread;

public static void addMessage(final String s) {
    thread = new Thread() {
        @Override
        public void run() {
            String data = Message.send(s);
            addMessageToContainer(data);
        }
    };
    thread.start();
}

public static void addMessageToContainer(String data) {
    //Do some stuff with the data
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //This code here will not be executed.
}

So normally, of course I can execute the code before I call the join function. 因此,通常情况下,我当然可以在调用join函数之前执行代码。 But I have to load after this thread execution a webview with some content. 但是我必须在此线程执行后加载包含某些内容的Web视图。 So when I do remove the join , it will give me the following error message: 因此,当我删除join ,它将给我以下错误消息:

java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'Thread-9072'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {5ac9b39} called on null, FYI main Looper is Looper (main, tid 1) {5ac9b39})

So what can I do to load the content after the thread has executed? 那么,在线程执行后如何加载内容?

Join doesn't kill a thread. Join不会杀死线程。 Join waits until that thread kills itself. Join等待,直到该线程杀死自己。 So that code would be executed- just at some time in the future, when that thread decides its done. 因此,该代码将在将来某个时间由该线程决定完成时被执行。 Calling wait on a thread from that thread will cause it to deadlock and never do anything, yet never die. 从该线程上调用线程等待将导致该线程死锁,从不执行任何操作,但永不消亡。 So in the case above where you're calling it from the thread itself, it will just hang forever. 因此,在上面从线程本身调用它的情况下,它将永远挂起。

There is no way to kill a thread directly, because its impossible to do so safely. 无法直接杀死线程,因为它不可能安全地杀死线程。 The way to kill a thread from the outside is to interrupt it, and let the thread check if it isInterrupted() every so often and if so kill itself. 从外部杀死线程的方法是中断它,并让线程每隔一段时间检查一次isInterrupted()以及是否杀死自己。 The way to kill a thread from the inside is to return from the runnable's run method. 从内部杀死线程的方法是从可运行的run方法返回。

Your webview error is totally unrelated. 您的webview错误是完全无关的。 You can only touch views on the main thread. 您只能触摸主线程上的视图。 Don't do anything with a webview on a thread. 不要在线程上使用webview进行任何操作。

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

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