简体   繁体   中英

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. My issue is that since the counter object is inside a Runnable it will need to be declared 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 .

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() . 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.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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