为什么这些代码使我的应用程序在 onPause 和 onResume 时停止?
Why these code make my application be stopped when onPause and onResume?
我有这样一个class
class C
{
MainActivity mainActivity;
boolean isPaused;
public void A()
{
B b = new B()
{
public void run()
{
isDone = true;
}
};
mainActivity.runOnUiThread(b);
while(!b.isDone && !isPaused)
{
try { Thread.sleep(1); }
catch(Exception e)
{
e.printStackTrace();
break;
}
}
}
}
abstract class B implements Runnable
{
public boolean isDone = false;
}
然后在实现GLSurfaceView.Renderer
的渲染器中调用
@Override
public void onDrawFrame(GL10 gl)
{
c.A();
}
c是C的instanceof,mainActivity在调用自身的onPause和onResume时调用GLSurfaceView.onPause和onResume。它还设置了 c 的 isPaused。
GLSurfaceView的onPause和onResume只是调用它的super的onPause和onResume。
然后当调用 onPause 和 onResume 时,我的应用程序被冻结了。为了找到问题,我删除了除我解释过的其他代码,但它仍然存在。
我该如何解决?
onDrawFrame
正在 UI 线程上执行。您将无限期地阻塞线程,因为您永远不会让 !b.isDone && !isPaused
评估为 false。你不应该在主线程 UI 上调用 Thread.sleep()
。
编辑:
其实我错了。从单独的线程调用渲染器以防止 UI 线程上出现此类阻塞。但是,在两个线程之间共享变量 (isDone) 仍然存在问题。这可以通过制作 isDone volatile
.
来克服
我有这样一个class
class C
{
MainActivity mainActivity;
boolean isPaused;
public void A()
{
B b = new B()
{
public void run()
{
isDone = true;
}
};
mainActivity.runOnUiThread(b);
while(!b.isDone && !isPaused)
{
try { Thread.sleep(1); }
catch(Exception e)
{
e.printStackTrace();
break;
}
}
}
}
abstract class B implements Runnable
{
public boolean isDone = false;
}
然后在实现GLSurfaceView.Renderer
的渲染器中调用@Override
public void onDrawFrame(GL10 gl)
{
c.A();
}
c是C的instanceof,mainActivity在调用自身的onPause和onResume时调用GLSurfaceView.onPause和onResume。它还设置了 c 的 isPaused。 GLSurfaceView的onPause和onResume只是调用它的super的onPause和onResume。
然后当调用 onPause 和 onResume 时,我的应用程序被冻结了。为了找到问题,我删除了除我解释过的其他代码,但它仍然存在。 我该如何解决?
onDrawFrame
正在 UI 线程上执行。您将无限期地阻塞线程,因为您永远不会让 !b.isDone && !isPaused
评估为 false。你不应该在主线程 UI 上调用 Thread.sleep()
。
编辑:
其实我错了。从单独的线程调用渲染器以防止 UI 线程上出现此类阻塞。但是,在两个线程之间共享变量 (isDone) 仍然存在问题。这可以通过制作 isDone volatile
.