SurfaceView和线程已经启动异常

时间:2012-10-03 18:49:03

标签: 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)

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

3 个答案:

答案 0 :(得分:5)

你的线程仍在运行,我猜你没有正确停止它。 你必须打断你的线程,或者我是如何解决它的。因此,不要使用setRunning和布尔值来运行你的线程,而是使用类似这样的东西:

启动它:

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();
}

我只是快速输入,但它应该给你一个想法。

答案 1 :(得分:0)

你可以这样做:

@Override
public void surfaceCreated(SurfaceHolder holder) {
    if (!thread.isAlive()) {
        thread.start();
    }
}

答案 2 :(得分:0)

这就是我解决这个问题的方法。在surfaceCreated方法中,线程的状态可能已更改为TERMINATED。您需要创建一个新线程。

@Override
 public void surfaceCreated(SurfaceHolder holder) {
     bgSurfaceThread = bgSurfaceThread.getState().equals(Thread.State.TERMINATED) ? bgSurfaceThread : new BackgroundSurfaceThread(BackgroundSurfaceView.this);
    bgSurfaceThread.setRunning(true);
   bgSurfaceThread.start();
}