I'm building an application where I'll have a SwingWorker thread that in itself spins off multiple worker threads. While these children threads do their work, what I want to achieve is that when the parent thread is interrupted, I want all the children to halt as well (i.e. for them to be interrupted as well). I understand that one way of achieving this is by using a global variable and making the children thread check this value within their own code. However, I was wondering whether this would be a right approach to take. Any comments/suggestions would be appreciated.
What I basically have is a simple UI with a JButton (initally the text of this is set to "Start"). When the button is clicked, the text changes to "Stop" and the parent SwingWorker thread is initiated. This thread is sent a directory location as a parameter. What this thread in turn does is generate a tread for each file that it finds in that folder to perform a specific operation. However, what I want to achieve is that, as soon as the JButton is clicked, the parent thread should stop scanning the folder and the children should halt scanning the file.
Just wanted to know what would be a suggested message passing methodology between the parent thread and the children thread for this operation. A global variable? Any comments/suggestions would be very helpful for me. Thanks!
One approach would be to override cancel()
in the parent worker and have it invoke cancel()
on each sub-worker before finally calling super.cancel()
.
Also consider a JTable
of executing sub-workers that can be cancelled individually.