android uses thread pool to speed up parallel computing and return computing results

Keywords: Mobile Java Android

###This method is suitable for a large number of data comparison, or single calculation without mutual influence

The thread pool has been used before, but in fact, there is no deep understanding and comparison when a large number of calculations are not encountered. Just this time, there is a need to use multithreaded parallel computing and return the calculation results at the same time. A large circle has been found on the Internet, which may be that the search method is wrong, and the corresponding introduction is relatively few, most of which are parallel computing without return results, Later, I found the corresponding method, but if the writing method is wrong, I will use pits

Here I will briefly introduce a simple example of using thread pool for multithreaded parallel computing and returning results

package com.lake.threadtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TestThreadPool.initTestThreadPool();

        try {
            runTestRunnable();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public List<Integer> runTestRunnable() throws Exception {
        List<Future<Integer>> list = new ArrayList<>();
        List<Integer> list1 = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<Integer> future = TestThreadPool.post(new testRunnable(i));
            list.add(future);//Return value is stored first and not retrieved
        }
        //There is a hole in the method of future.get(). Because the method of get is blocked, you need to call the above thread and then take a value separately. Otherwise, if you get directly in the above for loop, the thread execution will be blocked
        for (Future<Integer> future : list) {
            Log.e("lake", "results of enforcement=" + future.get());//Take it here alone
            list1.add(future.get());
        }
        return list1;
    }
	//runnable is usually used, but when you need to return a value, you have to use callable
    public class testRunnable implements Callable<Integer> {
        private int i;

        public testRunnable(int i) {
            this.i = i;
        }

        @Override
        public Integer call() throws Exception {
            Log.e("lake", "implement" + i);
            Thread.sleep(2000);
            Log.e("lake", "Execution completed" + i);
            return i;
        }
    }
}

Corresponding thread pool class

package com.lake.threadtest;

import android.util.Log;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThreadPool {
    private static TestThreadPool mInstance;
    private ThreadPoolExecutor mThreadPoolExec;
    private static int MAX_POOL_SIZE;
    private static final int KEEP_ALIVE = 10;
    BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
	//Initialize a custom thread pool
    public static synchronized void initTestThreadPool() {
        if (mInstance == null) {
            mInstance = new TestThreadPool();
        }
    }

    public static Future<Integer> post(Callable<Integer> runnable){
        Future<Integer> taskFuture = mInstance.mThreadPoolExec.submit(runnable);
        return taskFuture;
    }


    private TestThreadPool() {
        int coreNum = Runtime.getRuntime().availableProcessors();//Number of core threads
        Log.e("lake", "cpu Core number=" + coreNum);
        MAX_POOL_SIZE = coreNum + 1;//Thread pool size
        mThreadPoolExec = new ThreadPoolExecutor(
                coreNum,
                MAX_POOL_SIZE,
                KEEP_ALIVE,
                TimeUnit.SECONDS,
                workQueue);
    }

    public static void finish() {//Interrupt thread pool execution queue
        mInstance.mThreadPoolExec.shutdown();
    }
}

The above is a simple example of parallel computing with return value. The result of self-test is that when the number of multi threads is the number of core threads, it can achieve the optimal acceleration. It can probably reduce the calculation time to 3 / 8 of the original. If the calculation is small, it has no effect

Posted by youdontmeanmuch on Tue, 10 Dec 2019 11:28:00 -0800