Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to invoke a method in background Threads?  RSS feed

 
Joe Smith
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to invoke a method in background Threads?

I want to develop a Swing GUI application which can invoke methods in other classes in background threads. I want to spawn multiple threads to run the same method in parallel. I'm not sure how to pass arguments to the methods and how to get the return values.

Let's say we have a class called 'Operation' which has some methods:

Class Operation{
public String method_1(some arguments){}
public String method_2(some arguments){}
public String method_n(some arguments){}
}

Class SwingGui{
/* get user inputs
run method_x from the class Operation in m (m>1) background threads
and get the results from those threads and display them to the GUI
Background threads run the methods in a loop until the user hits the 'Stop' button in the GUI */
}

I know that there are many ways of doing this design, I'd appreciate your ideas and suggestions, how to use SwingWorkers, inner classes, etc.

Thanks

Joe
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, welcome to the Ranch!

The Sun Concurrency Tutorial is pretty good and will give you lots of depth on Threads. The short answer is to put your code in a class that implements Runnable and run it in a Thread:

At first you may think it's going to be really hard to extract the worker code and put it in a new class, but it often turns out to be a nice separation of concerns - a neat design.

If your Runnable needs to update the GUI along the way, you'll need to put the update code in yet another Runnable and use one of the SwingUtilities invoke* methods.

Give it a try and show us what you make!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!