首页 > 解决方案 > 修改在 Java 上定期执行的 runnable 的外部变量

问题描述

我试图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. 我的问题是,我该怎么做才能生成表格上显示的输出?

标签: javaandroidrunnable

解决方案


由于您的 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();;

推荐阅读