You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android计数器显示偶发少计数1的问题排查求助

问题原因
  • 循环执行顺序逻辑错误:当前代码是先休眠、更新UI,再递增计数。当counter走到final_value-1时,进入循环后更新的是还差1的数值,紧接着counter被递增到final_value,循环条件不满足直接退出,导致最终正确的数值从未更新到UI上。
  • 线程休眠存在中断风险:Thread.sleep(100)可能被系统中断,此时会直接跳过休眠执行后续逻辑,进一步增加计数不全的概率。
修复代码

调整执行顺序,先递增计数再更新UI,同时添加兜底的终值更新,确保最终数值100%显示:

final TextView t1 = (TextView) findViewById(R.id.text1);
final TextView t2 = (TextView) findViewById(R.id.text2);
winthread = new Thread(new Runnable() {
    float store_count = oldstore;
    int counter = 0;
    public void run() {
        // 先显示初始值
        updateTexts();
        while (counter < final_value) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // 被中断直接退出,避免乱序
                break;
            }
            // 先递增计数
            counter++;
            store_count = oldstore + counter * 5;
            // 再更新UI
            updateTexts();
        }
        // 兜底:确保最终值必被更新
        updateTexts();
    }

    // 抽离重复的UI更新逻辑,减少代码冗余
    private void updateTexts() {
        t1.post(() -> t1.setText(String.format("T1 $%.2f", store_count)));
        t2.post(() -> t2.setText(String.format("T2 %d", counter)));
    }
});
winthread.start();
额外优化提示
  • 优先使用Android官方推荐的CountDownTimer或Handler.postDelayed()实现定时UI更新,比手动管理线程更稳妥,能规避不少线程安全问题。
  • 给final_value、oldstore这类在线程中使用的变量添加final修饰,防止意外修改引发异常。

内容的提问来源于stack exchange,提问作者eng3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 07:30:53