一个线程中的 Thread.sleep() 会使 UI 线程也进入睡眠状态
我有一个扩展线程的类,在它的方法之一中,我添加了 Thread.sleep(5000) 来等待某些东西,我从 onCreate() 启动这个线程,就像这样
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyClass mc = MyClass();
mc.start();
mc.join();
// do something
}
,在 MyClass run 方法中,我做了类似的事情,
Class MyClass extends Thread {
public void run() {
sleep(15000);
// do something
}
}
问题是如果我运行 MyClass 线程(调用 sleep 方法),我也会看到 UI 线程睡眠 5 秒,为什么会发生这种情况?
i have class that extends thread and in one of its methodes i added Thread.sleep(5000) to wait for something, and i start this thread from onCreate() like this
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyClass mc = MyClass();
mc.start();
mc.join();
// do something
}
and in the MyClass run methode i do something like this
Class MyClass extends Thread {
public void run() {
sleep(15000);
// do something
}
}
the problem that i see the UI thread sleep for 5 second too if i run MyClass thread (that calls the sleep methode), why this happens ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,这就是你的问题:
这使得当前线程(即 UI)等待,直到
mc
表示的线程完成其run()
方法。无论如何,您想通过join()
实现什么目的。Well, here's you problem:
This makes the current thread (i.e. the UI) wait until the thread represented by
mc
has finished itsrun()
method. What were you trying to achieve with thejoin()
anyway.您是否正在执行 runOnUIThread 或在 MyClass 线程中使用处理程序?
如果您将新线程注释掉,一切正常吗?
Are you doing runOnUIThread or using handlers in your MyClass thread?
If you comment the new thread out, does everything work fine?
是的,该线程正在 UI 线程上运行。如果你想在单独的线程中运行,你需要使用 Runnable 或 ASyncTask 之类的东西。
请参阅 http://developer.android.com/resources/articles/painless-threading .html
Yes, that thread is running on the UI thread. If you want to run in a separate thread, you need to use something like a Runnable or ASyncTask.
Please see http://developer.android.com/resources/articles/painless-threading.html