Android Threading → Android Executor – Camposha

Android Threading

Android Threading

Android Executor

An Executor is an object that executes submitted Runnable tasks.

In this piece we want to look at executor with regards to Android Development.

 

Read more about Executor with regards to general Java Development here.

Quick Executor Examples

1. Using Executor with Handler

public DownloadStatusDeliveryImpl(final Handler handler) {
    this.mDownloadStatusPoster = new Executor() {
        public void execute(Runnable command) {
            handler.post(command);
        }
    };
}

2. Example 2

package executortest;

import java.time.LocalDate;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Client {

    public static void main(String[] args) {

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.gc();
            }
        }, 10000, 30000);

        ExecutorService executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>(), new RejectedExecutionHandler() {

                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        System.out.println("Runnable rejected :: " + LocalDate.now());
                    }
                });

        while (true) {

            for (int i = 0; i < 10; i++) {
                executorService.execute(new Runnable() {

                    public void run() {

                        System.out.println("Thread executed");
                    }
                });
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

3. Example 3

Example 4 – Android ThreadPoolExecutor

(a). MainActivity.java
(b). activity_main.xml

Download.

Leave a Reply

Your email address will not be published. Required fields are marked *

Price

Free

Rating

Not enough ratings to display
X