java - SurfaceView和线程已经启动异常

标签 java android multithreading thread-safety

检查 LunarLander 示例,它使用该代码来恢复抽屉线程:

public void surfaceCreated(SurfaceHolder holder) {
    // start the thread here so that we don't busy-wait in run()
    // waiting for the surface to be created
    thread.setRunning(true);
    thread.start();
}

结束:

public void surfaceDestroyed(SurfaceHolder holder) {
    // we have to tell thread to shut down & wait for it to finish, or else
    // it might touch the Surface after we return and explode
    boolean retry = true;
    thread.setRunning(false);
    while (retry) {
        try {
            thread.join();
            retry = false;
        } catch (InterruptedException e) {
        }
    }
}

但是当我执行该项目时,按主页按钮并恢复崩溃的应用程序

 java.lang.IllegalThreadStateException: Thread already started.
    at java.lang.Thread.start(Thread.java:1045)
    at com.example.android.lunarlander.LunarView.surfaceCreated(LunarView.java:862)
    at android.view.SurfaceView.updateWindow(SurfaceView.java:533)
    at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:226)
    at android.view.View.dispatchWindowVisibilityChanged(View.java:5839)
    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)
    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)
    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)
    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)

我在其他示例中看到过这种处理后台线程的方法,但它崩溃了。它有什么问题吗?

最佳答案

你的线程仍在运行,我猜你没有正确停止它。 你必须中断你的线程,否则我就是这样解决的。因此,不要使用 setRunning 和 boolean 值来使线程运行,而是使用如下所示的内容:

启动它:

public void surfaceCreated(SurfaceHolder holder) {
    thread.start();
}

在线程中:

public void run() {

    try {
        while (true) {
            // code here
        }
    }
    catch (InterruptedException e) {
         //disable stuff here
    }
}

并阻止它:

public void surfaceDestroyed(SurfaceHolder holder) {
    thread.interrupt();
}

我刚刚快速输入了此内容,但它应该可以给您一个想法。

关于java - SurfaceView和线程已经启动异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12714887/

相关文章:

java - 从 web.xml 中的库导入 servlet

Retrofit 响应中的 Android 空指针异常

android - NoSuchMethodError 当我使用 android.widget.RelativeLayout.setBackground

linux - 进程和线程在 Linux 中有什么区别?

C#,多线程 - 表单不更新

java - 为什么表达式 (double.MinValue < double.MinValue + 1) 返回 false?

java - 如何通过 <T> 通用类型使用现有的 HashMap?

c# - Parallel.Foreach 委托(delegate)调用另一个委托(delegate)

java - NBody代码在Java中不起作用-我需要修复什么?

jquery - Android jquery ajax 错误长度要求