简体   繁体   English

为处理程序运行的递归Runnable存储运行计数的最佳方法?

[英]Best way to store a run count for a recursive Runnable that is run by a Handler?

final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (counter <= 200) {
                    doThing();
                    counter++;
                    handler.postDelayed(this, 50);
                }
            }
        }, 0);

In the above code I have a Handler running a Runnable. 在上面的代码中,我有一个运行Runnable的处理程序。 My issue is that since the counter object is inside a Runnable it will need to be declared final. 我的问题是,由于计数器对象位于Runnable内部,因此需要将其声明为final。

What is the best way to handle this incrementing value? 处理此递增值的最佳方法是什么?

Currently I am simply using a counter object but I feel it should be easier: 目前,我只是使用一个计数器对象,但我觉得它应该更容易一些:

class Counter {
        int count;

        Counter() {
            count = 0;
        }

        public void addOne() {
            count++;
        }
    }

There are already classes that you could use instead, like AtomicInteger , or similar, but slightly different LongAdder . 已经有一些类可以代替使用,例如AtomicInteger或类似的类,但是LongAdder稍有不同。

You instantiate an object of that class, and then you can simply invoke various methods that will change the internal value of that object. 您实例化该类的对象,然后可以简单地调用各种方法来更改该对象的内部值。

These classes also provide the required thread safety. 这些类还提供了所需的线程安全性。 Without that property, it is rather unlikely that your counter will count up correctly! 如果没有这个属性,这是相当不可能的 ,你方会正确计算了!

Rather than using postDelayed() , you could use sendMessageDelayed() . 除了使用postDelayed() ,还可以使用sendMessageDelayed() You could send a Message that indicates that you want to run that runnable, and then use the arg1 field to store the current count. 您可以发送一条Message ,指示您要运行该可运行对象,然后使用arg1字段存储当前计数。

private static final int WHAT_DO_WORK = 1;
final Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        if (msg.what == WHAT_DO_WORK) {
            doWork(msg.arg1);
        }
    }
};
private void doWork(int counter) {
    if (counter <= 200) {
        doThing();
        int arg1 = count + 1;
        Message message = Message.obtain(handler, WHAT_DO_WORK, arg1, 0);
        handler.sendMessageDelayed(message, 50);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM