Julian
Julian

Reputation: 3869

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. 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. But I have to load after this thread execution a webview with some content. So when I do remove the join, it will give me the following error message:

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?

Upvotes: 0

Views: 100

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93678

Join doesn't kill a thread. Join waits until that thread kills itself. 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. The way to kill a thread from the inside is to return from the runnable's run method.

Your webview error is totally unrelated. You can only touch views on the main thread. Don't do anything with a webview on a thread.

Upvotes: 3

Related Questions