-1

I am new to threading, but I need to use threads in order to make my javafx application work. My problem is that I need to perform a lot of calculations in my program, and update the UI periodically in between. I am aware that making calculations in the javafx thread is blocking the UI update, so I need to move that work to another thread.

What I need to know, since I have never worked with threads before is, what is the best way to periodically start that thread, do part of the calculations, and send the results back to the javafx thread.

Juan González
  • 177
  • 1
  • 3
  • 10
  • 3
    Can you be more specific, e.g. post a simple example of what you are trying to do? It's probably easier for you to learn this by first seeing some relevant examples, rather than a general description of how it works, and a good answer to the question the way it is currently phrased would basically need to be an entire tutorial on multithreading. – James_D Oct 01 '17 at 17:16
  • This [example](https://stackoverflow.com/a/44056730/230513) calculates results in the background and publishes interim results for the listening GUI to display. – trashgod Oct 01 '17 at 17:28
  • The program is an implementation of the game of life, basically, what I want to do is render the canvas showing the state of the cells , wait some time, and then update the cells and render the canvas again. I have been able to do this already, however, using an scheduled executor service, so I guess I asked too soon – Juan González Oct 01 '17 at 21:09
  • 1
    Can't you do that with an `AnimationTimer`? Then you don't need threads at all. – James_D Oct 01 '17 at 21:16
  • Seems like a good option, I didn't know that class existed. I'm fine with my solution since it does its job, but maybe I will try rewiting the code using that to make it more clear. – Juan González Oct 01 '17 at 21:28

1 Answers1

1

Generally, you use interfaces (like the Runnable interface) or a message bus library to preform "subscriptions" to thread events, which are named "callbacks."

Implementing callbacks in Java with Runnable

The "Observer Pattern" is broadly something to research. Or "Publish Subscribe" (not related to any one library or tool like Google PubSub)

RxJava exposes some good patterns around this, but may be more complicated than necessary.

Periodic results require a Timer-like object, but the idea is the same.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245