doInBackground()
runs, unsurprisingly, in the background. That is, it is executed in another thread. So you can not rely in the order of execution of that code, and your printing code. So the contents of trainsList
can be modified before, after, or during the printing. You'd need to add some synchronization if you really need the results immediately (Usually you don't. That's the whole point in running the task in another thread to avoid waiting for it to be completed).
Most likely the correct solution is not have the printing code there at all, and let the SwingWorker
do it's work the way it's intended. The results are available in a thread safe way in done()
(and in process()
for anything you need the quickly after the sub task is ready).
In the second run you get "No name", because you never reset the names to anything else, so they are what they have been set to in the previous run.