Question

I want to be able to wait to thread to return a value from some calculations done on another class. Let me post some code:

public class ClassA implements Runnable{

public boolean threadRunning ; 
public String value  ; 

public ClassA() {
    ...
    }

 public String getValueFromServer() {

  //call to a method in the server that does some calculation

  ClassB.sendPetitionToServer() ;
    t=new Thread (this) ;   
    threadRunning = true ; 
    t.start();
    return value
      }

    public void run()
          {
     while(threadRunning)   
        {
        checkValue ()
        }
      }


      public void checkValue () {
       String value = ClassB.getInstance().getValue ;
       if (value!=null) {
       threadRunning = false ; 
       }

     }

     }

The question is, how can I wait for the thread to return a value from the method from ClassB.SendPetitionFromToServer()? The method ClassB populates the value but has to make some calculations that take time (5-8 seconds). ClassB is not Runnable, is a simple class. Maybe should I make another class that stores the value and notify ClassA.

To summarise my question (Maybe is to confusing or even my approach just plain stupid).

I am developing a Java WebApp. I have a ClassA that implements Runnable interface. This class has a method that needs to retrieve some information from another ClassB that needs to perform some quite heavy calculations that take time (retrieving some info from MySQL, done some calculations with the info...). How can I stop the method from ClassA until I get the response from ClassB? Is there anyway to do it?

Thanks in advance

Was it helpful?

Solution

You can join() on the thread and then collect a value from a variable populated by the thread.

However I would instead investigate Executors and Futures, so you can spawn a thread via an Executor, get a Future and then call Future.get(). It's a nicer, higher-level mechanism for getting results from threads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top