Mes
Mes

Reputation: 1

how can I get array values back from a thread

I have a thread, in Java, putting the first 100 Fibonacci numbers in an array. How do I get the numbers back from the thread. Is there an interrupt, handling, exception, implements, extends? I have been adding things and the trial and error is not getting me anywhere to understanding.

import java.util.Scanner;
import java.io.*;
import java.lang.Thread;      //don't know if this is needed

public class FibThread extends Thread{

    public FibThread (){
       super();                   
 }
 public void run(int inputNum){
     System.out.println(inputNum);
     long[] fibArray = new long[inputNum];
     fibArray[0]=0;
     fibArray[1]=1;
     fibArray[2]=1;
        for(int i = 3; i<inputNum; i++){
            fibArray[i]= fibArray[i-1] + fibArray[i-2];
       // }
            //System.out.println( );
       // for(int j = 0; j<= inputNum; j++){
            int output = (int) fibArray[i];
            System.out.println(output);

        }

 } 

 public static void main(String[] args){   
        Scanner keyboard = new Scanner(System.in);

        FibThread threadOne;
        int inputNum, itter, output;
        System.out.println("Please enter the number of Fibonacci numbers to be generated: ");
        itter = keyboard.nextInt();

        //inputNum = itter;


        threadOne = new FibThread();

        threadOne.start();


      //  for(int j = 0; j<= inputNum; j++){
       //   int output = (int) fibArray[j];
        //  System.out.println(output);

 }   


}

Upvotes: 0

Views: 88

Answers (1)

Andrzej Doyle
Andrzej Doyle

Reputation: 103817

If you have a "task" that returns a value, make it a Callable.

If you want the callable to run in a background thread, then instead of handling the creation and execution of threads yourself, it's generally better to abstract this through an ExecutorService. A caller can interact with the service by passing in a Callable, and getting back a Future that will be populated with the value when the calculation has completed.

To modify your example, renaming FibThread to FibCalc:

public class FibCalc implements Callable<Integer> {
    // We need some way to pass in the initial input - must be through the
    // constructor and we'll store it here
    private final inputNum;

    public FibCalc(int inputNum) {
        this.inputNum = inputNum;
    }

    public int call() {
        // The same as your run() method from before, except at the end:
        ...
        return output;
    }
}

// And now for your main() method
public static void main(String[] args) throws Exception {
     // As before up to:
     ...
     itter = keyboard.nextInt();

     // Create a very simple executor that just runs everything in a single separate thread
     ExecutorService exec = Executors.newSingleThreadExecutor();

     // Create the calculation to be run (passing the input through the constructor)
     FibCalc calc = new FibCalc(itter);

     // Send this to the executor service, which will start running it in a background thread
     // while giving us back the Future that will hold the result
     Future<Integer> fibResult = exec.submit(fibCalc);

     // Get the result - this will block until it's available
     int result = fibResult.get();

     // Now we can do whatever we want with the result
     System.out.println("We got: " + result);
}

If you absolutely have to create a Thread object yourself (due to artificial constraints on a homework question, or something like that - I can't see why one would realistically do this in reality), then the approach has to be different. You can't return a value because run() must return void due to the interface. So my approach here would be to store the result in a local variable of the FibThread class, and then add a method to that class (e.g. public int getResult()) which returned that variable.

(If you're doing it this way, bear in mind that you'll have to handle the concurrency issues (i.e. letting the caller know the result is ready) yourself. A naive approach, where the main method starts the thread and then immediately calls getResult(), means that it will almost certainly get an "empty" result before the calculation has finished. A crude solution to this problem would be calling join() on the spawned thread, to wait for it to finish before accessing the result.)

Upvotes: 1

Related Questions