简体   繁体   中英

Passing a method as a parameter in JAVA

I'm looking for how to pass a method as a parameter in Java. Every method I found doesn't fit my problem. I'm doing an Android image processing app and I want to make every processing algorithm run in a thread.

The problem is every method I have found (lambda, Callable) doesn't work. Here is my ImageProcessing class so you can see the different prototypes.

public class ImgProcessing {

    private static Img image;

    public static void colorize(int chosencolor) {
        //Stuff
    }

    public static void histogramEqualization() {
        //stuff
    }

    public static void extendDynamism() {
        //stuff
    }

    public static void toGray() {
        //stuff
    }

    public static void convolution(int n, int typeFilter) {
        //stuff
    }

    private static void calculConvolution(float[][] filtermatrix, int sizefilter) {
        //stuff
    }

    public static void overexposure() {}

    public static void isolate(int colorValue) {

    }

    public static void sepia() {

    }
}

The goal here is to cut the pixel array in many parts as processor cores and create a thread that processes a part of the array. I'm trying to avoid code duplication so I want to have a generic Thread method to which I pass my processing method.

Something like :

public class Worker implements Runnable {
    private final int numberOfIterations;
    private final float[] x = new float[12000];
    Func myFunc;

    public Worker(int numberOfIterations, Func myFunc) {
        this.numberOfIterations = numberOfIterations;
        this.myFunc = myFunc;
    }

    public void run() {

    }

    public void initThread{
        // *** Main Thread ***
        Thread[] threads = new Thread[8];

        for (int i = 0; i < 8; i++) {
            //Creating threads and calling myFunc method.
        }

        for (int i = 0; i < 8; i++) {
            threads[i].join();
        }
    }
}

I guess you should consider create an interface class like ImageProcessing with a method process . Create methods as classes which inherit ImageProcessing . So myFunc will be ImageProcessing class which you can pass as class you needed.

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