我有这个帖子:
private class MyThread extends Thread{
public void run(){
try {
sleep(10000);
Utils.stopTimer();
} catch (InterruptedException e) {
Log.d(TAG, "interrupted");
}
}
}
然后我开始了线程。但是线程阻止了主UI线程,导致它无法响应用户交互。
答案 0 :(得分:7)
致电myThread.start()
而不是myThread.run()
。
执行后者不会导致代码在不同的线程中执行,而只是调用当前上的run
方法(例如UI)线程 - 就像任何其他常规方法调用一样。
摘录链接文档:
start
使此线程开始执行; Java虚拟机调用run
方法[在已启动的线程中] ..
答案 1 :(得分:4)
你需要调用thread.start()来启动一个线程,当你调用run()方法时会自动执行。
Calling this thread will also blocks the UI thread, you need to call it Async Task or in runonuithread.
答案 2 :(得分:1)
最好使用AsyncTask
或Activity.RunOnUIThread
来执行此类代码。