John Baum
John Baum

Reputation: 3331

Updating a view from parallel threads results

I have two threads in my data model layer that run in "parallel" and both compute some values. I have an mvc pattern setup so my data model has two arrays, each responsible for the values generated from each of my threads. How can i tell my view that my arrays have new data without blocking on the main UI?

My threads are running on a timer ever x seconds and generate one integer each. Each of these needs to be added to an array and, when added, the view should get a notification via the observer pattern to update the screen according to the two arrays' updated values. This should happen without ever blocking on the main ui thread. So i cant really do while(true) or set a futureValue for each thread as that would make my ui wait until the threads are done. What can i do?

Upvotes: 0

Views: 105

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328556

This seems like a pretty complex approach. Here is mine:

  • Create a blocking queue
  • Get rid of the arrays and have each thread put their results in the queue
  • Start a worker thread that waits for items in the queue
  • Use SwingUtilities.invokeLater() in the worker thread to update the UI.

Upvotes: 0

jboi
jboi

Reputation: 11892

You will always:

  • Extend the array class that contains the results and overwrite the add method
  • Put in the add at the end the code to inform UI-Thread
  • To synchronize the updates, you can use a ExecutorService with just one Thread, that you get with Executors.newSingleThreadExecutor(). In that you submit() the code to inform UI-Thread.
  • Your execution should be part of a WorkerThread and be handled in doInBackground
  • In the done() method you update the User interface (done() is executed on Swing's event dispatch thread)

See here for more information on Threads and Swing

Upvotes: 1

Related Questions