java - 修改在 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
. 我的问题是,我该怎么做才能生成表格上显示的输出?
解决方案
由于您的 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();;
推荐阅读
- c# - c# HttpClient - 从传输流中接收到意外的 EOF 或 0 字节
- java - 如何自定义我使用 html 创建的 WhatsApp 分享按钮的颜色、字体、背景颜色和对齐方式?
- html - 在 Eclipse 中使用 J2EE 服务器配置 JSP
- node.js - AWS lambda 事件重新处理请求
- python-behave - Python表现Gherkin Step参数获取编译时间数字预期异常
- android - 如何在 gitlab ci 中接受 android sdk 的许可证
- github - 当您的分支 github 桌面上存在更改时无法恢复存储
- python - 使用队列数组的广度优先搜索
- javascript - 递归一维嵌套数组以更新父节点
- pyserial - 如何将 linux gpio 子系统与 PySerial 一起用于 RS485 DE 信号 (RTS)