Sk1X1 Sk1X1 - 6 months ago 10
Java Question

Easy way to call method in new thread

I'm writting small app and now I discovered a problem.
I need to call one(later maybe two) method (this method load something and return the result) without lagging in window of app.

I found classees like Executor or Callable, but I don't understand how to work with those ones.

Can you please post any solution, which helps me?

Thanks for all advices.

edit. The method MUST return the result. This result depends on parametrs.
Something like this:

public static HtmlPage getPage(String page) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
return webClient.getPage(page);
}


This method works about 8-10 seconds. After execute this method, thread can be stoped. But I need to call the methods every 2 minutes.

edit3. I edited code with this:

public static HtmlPage getPage(final String page) throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
Thread thread = new Thread()
{
public void run()
{
try
{
loadedPage = webClient.getPage(page);
}
catch (FailingHttpStatusCodeException | IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
thread.start();
try
{
return loadedPage;
}
catch (Exception e)
{
return null;
}

}


With this code I get error again (even if I put return null out of catch block).

Answer

Firstly, I would recommend looking at the Java Thread Documentation.

With a Thread, you can pass in an interface type called a Runnable. The documentation can be found here. A runnable is an object that has a run method. What you start a thread, the thread will call whatever code is in the run method of this runnable object. For example:

Thread t = new Thread(new Runnable() {
         public void run()
         {
              // Insert some method call here.
         }
});

Now, what this means is when you call t.start(), it will run whatever code you need it to without lagging the main thread. This is called an Asynchronous method call, which means that it runs in parallel to any other thread you have open, like your main thread. :)