Basically, I have a graphical swing application. I need to use UDP to send and receive data, but I don’t want any receive(packet) calls in the application’s code. I decided to run the receiving end of the program on a separate thread. The thread has an int field that gets updated to the value from incoming packets. How would I get the value of this field from the thread. Can I just call the get method for the field, or do I have to interrupt the thread first?
Share
Although the GUI thread can read the int getter safely (assuming appropriate synchronization or volatile variable), consider taking the time to use SwingWorker as it will make your app more responsive. Basically you replace your custom thread with a SwingWorker object. The code you now have in
run()goes inSwingWorker.doInBackground().You start the worker and the
doInBackgroundcode executes in a separate thread. Presumably this is a UDP receive loop. When your loop receives an new int, you callpublish(still in the background thread). This will cause another SwingWorker methodprocess(which you have overridden with some custom code) to be called in the event thread. Here you can safely update your GUI because you are running in the event thread.This eliminates the need to create timers to poll getter of the UDP thread. The UI is more responsive because the receive -> publish -> process sequence is pretty quick.