修改在 Java 上定期执行的 runnable 的外部变量

Modify external variable of runnable executed periodically on Java

我正在尝试每五秒在 Android 上执行一个 Runnable 应该在数据库中插入这些值:

value | seconds delayed
  1            0
  2            5
  3            10
  4            15
  3            20
  2            25
  1            30

我的方法如下:

public class MainActivity extends AppCompatActivity{
    public static int currentValue;
    public static int directionSign;

    protected void onCreate(Bundle savedInstanceState) {
        generateData();
    }

    public void generateData(){

        currentValue = 1;
        int directionSign = 1;

        while(!(directionSign == -1 && currentValue == 0)){

            Handler handler=new Handler();
            Runnable r=new Runnable() {
                public void run() {
                    long currentTimestamp = System.currentTimeMillis();
                    db.insertValue(currentTimestamp, currentValue);
                }
            };

            //Insert two registers for each state
            for(int i=0; i<2; i++) {
                handler.postDelayed(r, 5000);
            }

            if(currentValue == 4){
                directionSign = -1;
            }

            currentValue+= directionSign;


        }

        handler.postDelayed(r, Constants.MEASUREMENT_FREQUENCY);

    }
}

然而,此代码卡在 value 1。我的问题是,我该怎么做才能生成显示在 table?

上的输出

由于您的 while 循环迭代了 7 次并且您生成了 14 个线程,所有线程将在 5 秒后立即执行,而不是每 5 秒执行一次。因此,对于您的用例,您只能创建一个每 5 秒写入一次数据库的线程:

new Thread(new Runnable() {
            public void run() {
                int currentValue = 1;
                int directionSign = 1;
                while(!(directionSign == -1 && currentValue == 0)) {
                    long currentTimestamp = System.currentTimeMillis();
                    db.insertValue(currentTimestamp, currentValue);
                    if(currentValue == 4){
                        directionSign = -1;
                    }
                    currentValue+= directionSign;
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();;