SwingWorker in Java (initial question)

I'm relatively new to multithreading and want to do a background job using a Swingworker thread - a method that gets called returns virtually nothing, but I would like to be notified when it is completed.

Of all the tutorials I've seen on the Internet on using SwingWorkers, such as

new SwingWorker<String, Void>; 

Will I announce that Void, Void is suitable since there is no data returned?

Code that still doesn't work doesn't work:

 private void crawl(ActionEvent evt) { try { SwingWorker<Void, Void> crawler = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { Discoverer discover = new Discoverer(); discover.crawl(); return null; } @Override protected void done() { JOptionPane.showMessageDialog(jfThis, "Finished Crawling", "Success", JOptionPane.INFORMATION_MESSAGE); } }; crawler.execute(); } catch (Exception ex) { JOptionPane.showMessageDialog(this, ex.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE); } } 

Any feedback / recommendation would be greatly appreciated, as multithreading is a large programming area in which I am weak.

+4
source share
2 answers

The code looks fine ... It should work. Perhaps the traversal method never ends ... What happens if you debug the code and run it until the lines where you return null, and see if the traversal method completes ...

+2
source

I would recommend monitoring the status of your workaround (does it ever end?), And also wrap it in a try {...} catch block in your doInBackground. Either this, or get () is called from your prepared method. In any case, you should catch any exceptions that occur during the traversal.

+1
source

Source: https://habr.com/ru/post/1305049/


All Articles