Reputation: 530
In Java, how can I pass an event from a child Thread to the main thread, without freezing the main thread in a loop ?
Online I could only find solutions that involve the main thread stuck in an infinite while loop checking for events in a shared thread-safe event FIFO queue
(where the child puts the events).
Then sleeping for x
sec and starting again.
I need the main Thread active and doing other things, such as being able to process events form the gui. And when something happens in the child thread, the main thread has to, say, invoke .eventHappened()
.
Upvotes: 1
Views: 1396
Reputation: 1426
To avoid freezing the UI this should do the trick:
1) Incoming work concurrent queue where a worker thread or pool of worker threads are checking in their run methods.
2) Work done concurrent queue where a listener thread, different from the UI thread, checks in a loop. The listener thread invokes updates to the UI using asynchronous facilities/methods to avoid UI exceptions.
So the UI thread feeds the incoming work queue with events or data. The worker threads pick it up, do the work and post results to work done queue.
Listener thread checks for new items in the work done queue and post results asynchronously to the UI.
Upvotes: 1
Reputation: 174
If you really need to use a child thread that way, you would probably need to use a concurrent queue.
If you are using swing you can use SwingUtilities.invokeLater() to execute code. It would then run it in a backgroundt thread instead of using a child thread manually.
Upvotes: 0