【问题标题】:Some Logical error in handler in AndroidAndroid中处理程序中的一些逻辑错误
【发布时间】:2018-03-11 01:28:26
【问题描述】:

我是安卓初学者。

我想要什么: 在这里,我试图实现该子处理程序应该每秒调用 10 次主处理程序。并且那个主处理程序应该会持续到 20 秒。

问题: 检查我\我是否使用了日志但它不起作用。它有时会进入子处理程序 8 次或有时 9 或 10 次。 是否有任何逻辑错误或有任何其他更好的方法来实现这一点? 谢谢。

我的代码:

int i=0;
int cont;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        i++;
        cont = 1;
        Log.e("main count", i + "");
        final Handler handler1 = new Handler();
        handler1.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (cont <= 10) {
                    Log.e("sub count ", cont + "");
                    cont++;
                    handler1.postDelayed(this, 100);
                }
            }
        }, 100);
        if (!(i == 20)) {
            handler.postDelayed(this, 1000);
        }
    }
}, 1000);

【问题讨论】:

  • @pskink-实际上,将来我想在主处理程序和其他子处理程序中调用不同的方法..
  • 为什么需要多个 Handlers?
  • @jimmyB-我希望每一秒 y 方法都会被多次调用,而主处理程序 x 方法会被调用一次。
  • 如果您希望我们了解您在做什么,您将不得不格式化您的代码并使用描述性变量名称

标签: java android multithreading android-handler postdelayed


【解决方案1】:

使用 Handler 很难以精确的时间执行代码,因为您必须自己测量时间。 使用像ScheduledThreadPoolExecutorTimer 这样的内置类要容易得多。我推荐第一个,因为它需要对代码进行较少的更改。您应该根据自己的要求选择 scheduleAtFixedRate() 或 scheduleWithFixedDelay() 方法之一。

final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
final ScheduledFuture mainFuture = executor.scheduleWithFixedDelay(new Runnable() {
    public void run() {
       if (i < 20) {
           Log.e("main count ", i + "");
           i++;
       } else {
           mainFuture.cancel(true);// stop after 20 executions
       }          
},
0, /*initial wait time*/
1, /* time between consecutive runs */
TimeUnit.SECONDS);

final ScheduledFuture subFuture = executor.scheduleWithFixedDelay(new Runnable() {
    public void run() {
       if (cont < 20 * 10) {
           Log.e("sub count ", cont + "");
           cont++;
       } else {
           subFuture.cancel(true);// stop after 200 executions
           executor.shutdown();
       }          
}, 
100, /*adjust this according to the desired sequencing of the count tasks */
100, /* time between consecutive runs */
TimeUnit.MILLISECONDS);

您还可以使用单个 ScheduledFuture 并在每执行 10 次子计数代码后执行主计数代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    相关资源
    最近更新 更多