Search code examples
javamultithreadingrunnable

Java 7 run selected method in thread


In my code Java 7 (and no cannot use Java 8+) I try to run selected method in thread from one class file but somehow cannot grasp how to do it for methods without any parameter passed. This is what I have so far:

Tools.java

public final class Tools implements Runnable {

    private int number; // necessary for checkInt(int number) to work
    private int string; // necessary for checkString(String string) to work

    public void run() {
        
    }

    public static int checkInt(int number) {
        return number;
    }

    public static String checkString(String string) {
        return string;
    }

    public static String checkNoParamString() {
        //doing some stuff
        return string;
    }

    public static String checkNoParamInt() {
        //doing some stuff
        return int;
    }
}

App.java

public static void main(String[] args) {

    Thread tstring = new Thread(Tools.checkString("test"));
    Thread tint = new Thread(String.valueOf(Tools.checkInt(10)));
    Thread tNoString = new Thread(Tools.checkNoParamString()); //<-does not work
    Thread tNoInt = new Thread(Tools.checkNoParamInt());  //<-does not work

    tstring.start();
    tint1.start();
    tNoString.start();
    tNoInt.start();

}

Can someone tell me what to do to make it work with not parameterized methods, if possible without creating new java class files for every single method or using Java 8 ?


Solution

  • The pre-Java 8 lambda equivalent would be anonymous classes:

    Thread tstring = new Thread(new Runnable() {
        @Override
        public void run() {
            Tools.checkString("test"));
        }
    });