Home > Software design >  Java save thread result in a variable from main class
Java save thread result in a variable from main class

Time:06-04

I have a thread created by implementing the Runnable interface. My task is this: the thread should count (starting from 0) and save the value it has reached to a variable which is part of the main class. I overrode the run method and did the counting but how I can save this value to the main's variable? Only with a getter is the solution? My thread class:

public class myThread implements Runnable {
    private static int count = 0;
    private final int length;

    public myThread (int length) {
        this.length = length;
    }

    @Override
    public void run() {
        while (count < this.length) {
            increaseValue();
        }
    }

    private void increaseValue() {
        synchronized (ThreadFirstExercise.class) {
            if (count < this.length) {
               this.count  ;
            }
        }
    }
}

main:

public class Main {
    public static void main(String[] args) {
      int result; // this is the variable where I want to save the counting result of my thread
      (new Thread(new ThreadFirstExercise(10000))).start();
}
}

CodePudding user response:

You can either use a Callable that returns a Future. Or you could use a wrapper Object in the main method that contains the integer.

  • Related