2

我希望我的程序在我的情况下等待 10 秒,但它不起作用我尝试使用Thread.sleep(10000);但它不是 10 秒

while (true) {
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 5; j++) {
            if (matrixVacancy[i][j] == 1) {
                completeParking(i, j, R.color.vaga_ocupada);
            } else {
                completeParking(i, j, R.color.cor_chao);
            }
        }
    }
    try {
        Thread.sleep(10000);
    } catch (InterruptedException ex) {
    }

    int a, b, c, d, e, f, g, h, i;

    a = (int) (Math.random() * 2); // indice i
    b = (int) (Math.random() * 5); // indice j
    c = (int) (Math.random() * 2); // tem ou nao carro

    d = (int) (Math.random() * 2); // indice i
    e = (int) (Math.random() * 5); // indice j
    f = (int) (Math.random() * 2); // tem ou nao carro

    g = (int) (Math.random() * 2); // indice i
    h = (int) (Math.random() * 5); // indice j
    i = (int) (Math.random() * 2); // tem ou nao carro

    matrixVacancy[a][b] = c;
    matrixVacancy[d][e] = f;
    matrixVacancy[g][h] = i;
}

我该怎么做?让我等 10 秒?

4

3 回答 3

14

取决于你试图睡觉的线程。您也可以将您的方法放在一个单独的线程中并在那里执行您的方法。这样你的应用程序就不会挂起/休眠

private class TimeoutOperation extends AsyncTask<String, Void, Void>{

    @Override
    protected Void doInBackground(String... params) {

        try {
            Log.i(TAG, "Going to sleep");
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        Log.i(TAG, "This is executed after 10 seconds and runs on the main thread");
        //Update your layout here
        super.onPostExecute(result);
    }
}

要运行此操作,请使用

new TimeoutOperation().execute("");
于 2012-12-07T14:34:28.100 回答
0

改变:

    catch (InterruptedException ex) {
    }

至:

    catch (InterruptedException ex) {
        ex.printStackTrace();
    }

检查 logcat 以确保睡眠没有被中断。

此外,在调用 Thread.sleep 之前和之后放置一些 Log 语句,打印出经过的时间。

Logcat 是你的朋友。:)

于 2012-12-07T14:39:17.610 回答
0

First I'd break point to see if your sleep is even called. Second I'd print the exception when your catching the InterruptException. Your sleep is correct so there's no reason it shouldn't be working so either someone is interrupting you or your not even getting to the sleep function.

于 2012-12-07T14:30:47.657 回答