我有一个问题,用于终止线程的 join
方法没有执行该方法的其余部分,该方法也在线程中启动。这是一个代码示例:
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.
}
所以通常情况下,我当然可以在调用 join
函数之前执行代码。但我必须在该线程执行后加载包含一些内容的 WebView 。因此,当我删除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})
那么线程执行完毕后我该如何加载内容呢?
最佳答案
加入不会杀死线程。 Join 会等待,直到该线程自行终止。因此,该代码将在将来的某个时间,当该线程决定完成时执行。从该线程调用 wait 将导致该线程死锁并且永远不会执行任何操作,但永远不会死亡。因此,在上面的情况下,您从线程本身调用它,它将永远挂起。
没有办法直接终止线程,因为不可能安全地这样做。从外部杀死线程的方法是中断它,并让线程经常检查是否 isInterrupted() ,如果是,则杀死自己。从内部杀死线程的方法是从可运行对象的 run 方法返回。
您的网页 View 错误完全无关。您只能触摸主线程上的 View 。不要对线程上的 webview 执行任何操作。
关于java - Thread.join() 执行后执行相同方法中的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43285262/