0

Everyone know factorial right. I m practicing Thread and class relationship. My question is getting results from thread class. If you suggest callbacks, Can you implement callback class for this example.

public class factorial extends Thread {
    int sz = 0;
    List < String > ar = new ArrayList < String > ();
    public factorial(int n) {
        this.sz = n;
    }
    public void run() {
        int p = 1;
        for (int i = 1; i <= sz; i++) {
            p *= i;
            ar.add(p + "");
        }
    }
}
public class Test {
    public static List < String > ans = new ArrayList < String > ();
    public static void main(String[] args) {
        factorial f1 = new factorial(10);
        factorial f2 = new factorial(8);
    }
}
2
  • f1.start() should start the thread storing the incremental factorial values in the list ar. Not sure if i am getting your question. Commented Mar 16, 2016 at 18:36
  • where are mentioned stack, queue and callback in this code? Commented Mar 16, 2016 at 19:02

1 Answer 1

1

In your main:

// Start both threads
f1.start();
f2.start();

// Wait until they are finished
f1.join();
f2.join();

// Here are your lists
List<String> f1Strings = f1.ar;
List<String> f2Strings = f2.ar;

However, I can't help myself from codereviewing a bit:

  • Class names start with a capital letter (Factorial), and should be more descriptive, eg.: FactorialCalculatorThread
  • Don't access fields directly (like I did in the example above), use getters (getSomething) and use descriptive names!
  • Also separate concerns! I wouldn't calculate factorials, and also convert to string in one method.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.