减轻 Android UI 线程的繁重计算
我的 Android 应用程序使用特别大的计算,导致系统不断崩溃,因为它位于 Activity 中的 UI 线程上。 我对多线程没什么信心,所以我想获得一些关于如何正确执行多线程的提示。 这就是我
class ActivtyName extends Activity{
boolean threadcomplete = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//stuff
Runnable newthread = new Runnable(){
@Override
public void run() {
doBigComputation();
threadcomplete=true;
}
};
newthread.run();
boolean b = true;
while(b){
if(threadcomplete){
b=false;
startTheApp();
}
}
}
}
现在所拥有的,我很确定我所做的不是“正确的”。 (虽然它似乎有效。系统不会崩溃)。基本上,我不确定如何在没有这个布尔值、threadcomplete 的情况下告诉 UI 线程 newthread 已完成计算。有没有“正确”的方法来做到这一点?
My Android app employs a particularly big computation which keeps crashing the system because it is on the UI thread in the Activity.
I have little confidence in multithreading and so I want to get some tips on how to do it correctly.
This is what I have
class ActivtyName extends Activity{
boolean threadcomplete = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//stuff
Runnable newthread = new Runnable(){
@Override
public void run() {
doBigComputation();
threadcomplete=true;
}
};
newthread.run();
boolean b = true;
while(b){
if(threadcomplete){
b=false;
startTheApp();
}
}
}
}
Now, I am pretty sure what I have done is not "correct". (It seems to work though. The sistem doesn't crash). Basically, I'm not sure how the UI thread can be told that newthread has finished the computation without this boolean, threadcomplete. Is there a "correct" way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只是为了扩展 Marek Sebera 的评论,下面是有关如何在 AsyncTask 中实现这一目标的框架。
并称其为:
Just to expand a bit on Marek Sebera's comment, here's the framework on how you would accomplish that in an AsyncTask.
And to call it:
除了 Marvin 的回答之外,Android 开发者网站上还有一篇好文章 正是关于这一点。
In addition to Marvin's answer, there's a good article on the Android developer site about precisely this.
这不是启动线程的正确方法。你需要做:
That's not the correct way to start a thread. You need to do:
当我想使用线程时,我几乎有一个很大的 while 循环。我设置了一个始终为真的布尔条件,除非我想停止它。
我使用 Thread (http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html) 并重新实现 stop 方法,因为它已被弃用。因此,在我的 stop 方法中,我可以为循环变量添加一个假值。
为了终止线程,我使用 t.stop()。所以你可以在你的活动中做到这一点。
如果你想知道 Thead 何时停止,可以使用 t.isAlive()。如果线程 t 已启动,isAlive 将返回 true。
When i want to use threads, I've almost a big while loop. I put a boolean condition who's always true, except when I want to stop it.
I use Thread (http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html) and I reimplement the stop method because it's deprecated. So in my stop method I can put a false value to the loop variable.
To terminate the thread, I use t.stop(). So you can di that in your activity.
If you want to know when a Thead stops, you can use t.isAlive(). If the thread t is started, isAlive will return true.