Help with implementing Runnable in Java

I’m working on a java project with my team at work. To summarize, we have a main class that has a method that instantiates and calls a “Save” class. This “Save” class saves files back to a server with a couple of constructors and a handful of visible and non-visible methods. The class is CPU-intensive and time-consuming which prevents the main application from displaying a progress bar dialog window letting the user know the status of the save. They asked me to modify the “Save” class in a way that it will spawn off it’s own thread so the rest of the main application can do the smaller tasks of displaying information to the user.

Here is a general concept of it:

class MainApp{  
    ...

    private void doSave()
    {
        Save s = new Save();
        StatusWindow sw = new StatusWindow();

        if save_this
          s.saveThis(sw);
        if save_that
          s.saveThat(sw);

        ...
    }
    ...
}

class Save{
   ...

   public void saveThis(StatusWindow s)
   {
       //alot of code
       s.update;

   }
   public void saveThat(StatusWindow s)
   {
       //alot of code
       s.update;
   }
   ... // some non-visible methods, even more code
 }

I’m am currently a novice with threads in Java, but I have a basic understanding of how they work. From what I understand, a class that implements Runnable, when it is instantiated as a new thread, the run() method is executed. The problem is, since there are different methods for different types of saves for different types of files, how do I implement these methods into the run() method? Is the run() method the only method that gets executed when the class is instantiated in a new thread and .start() is called on it?

What would be a good solution to this issue? Would the “Save” class need to be redesigned to have it implement Runnable?

If more details are needed, please let me know. Thanks for any insight!

Update: Thanks everyone for the help! These solutions will come in handy for the future.

Answer

The simplest way is to make a runnable for each. Instead of parameters being passed into run, make them instance fields.

class SaveThatCommand implements Runnable {
     private final StatusWindow s;
     //constructor that initializes s
     public void run() {
        //save that code
        s.update();
     }
}

An easier way to accomplish this, depending on your requirements, is to make an anonymous inner class

public void doSave(final StatusWindow s) {
    if (saveThis) {
        Thread t = new Thread( new Runnable() {
            public void run() {
               saveThis(s);
            }
        });
        t.start();
    }
    //...
}

And you’re slightly incorrect: the run method is executed when it is passed into the constructor of a Thread and then start() is called on that thread.

Leave a Reply

Your email address will not be published. Required fields are marked *