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

最初に私はあなたの睡眠が呼ばれるかどうかを見るためにポイントを破ります。次に、InterruptExceptionをキャッチしたときに例外を出力します。あなたの睡眠は正しいので、それが機能してはいけない理由はないので、誰かがあなたを邪魔しているか、あなたが睡眠機能に到達していません。

于 2012-12-07T14:30:47.657 に答える
0

変化する:

    catch (InterruptedException ex) {
    }

に:

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

logcatをチェックして、スリープが中断されていないことを確認します。

また、Thread.sleepの呼び出しの前後にいくつかのLogステートメントを入れて、経過時間を出力します。

Logcatはあなたの友達です。:)

于 2012-12-07T14:39:17.610 に答える