Вопрос

my question is more about programming pattern than about a specific case.

I want to know how to manage better interactions between concurring threads.

Say I have that for example :

Class Ocean implements Runnable {
   Boat myBoat;

   // standard stuff

   @Override
   public void run(){
      // the boat navigates through the sees…
   }
}

And the following, which is a different thread because it has to run at the same time :

Class Radar implements Runnable {

    // standard stuff

    public int scanOcean(){
        // return boat.position();
    }
}

And both those classes are object of my Main method for example.

Now the question is : how can I access the methods inside another thread ? I looked up for it, but I couldn’t find any consistent and practical answer…

Some site refer to the volatile declaration for field that might be used by another thread, some tell about event listeners, others about event handlers… Should I use the standard Observer/Subject pattern ?

Thanks!

Silver Duck

Это было полезно?

Решение

I made good experiences with an intermediate helper object, holding only data to be shared like status info, abort flags etc shared between threads. That will not fit all cases, but it does quite often for me.

The helper instance should implement (and encapsulate) locking in its methods, getters and setters as required, so you don't have to deal with it on the outside.

Consistent, thread safe, easy to use.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top