Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling main thread from Runnable thread in java

i have implemented a Runnable interface to load the image tiles and i want to call the Main thread from this secondary thread for displaying the tiles. can anybody tell me how to call a Main thread from a Runnable Interface thread in Java.

thanks.

like image 424
sajjoo Avatar asked Dec 09 '10 10:12

sajjoo


People also ask

Does runnable Run main thread?

This Runnable runs on the current thread, i.e. the thread that invokes this code. It doesn't magically create, or constitute, another thread. Runnable. run() is only a method call.

How do I switch to main thread in Java?

The main thread is created automatically when our program is started. To control it we must obtain a reference to it. This can be done by calling the method currentThread( ) which is present in Thread class.

What is difference between calling wait () and sleep () method in Java multithreading?

Wait() method releases lock during Synchronization. Sleep() method does not release the lock on object during Synchronization. Wait() should be called only from Synchronized context. There is no need to call sleep() from Synchronized context.

What is the difference between calling start () and run () method of thread?

In Summary only difference between the start() and run() method in Thread is that start creates a new thread while the run doesn't create any thread and simply executes in the current thread like a normal method call. Why wait and notify methods are declared in Object Class?


1 Answers

Instead of Runnable you can use Callable<Set<Image>> which returns a set of loaded images. Submit this callable task to an executor, get the Future<Set<Image>> and wait for the loading thread to finish its job.

For example:

Future<Set<Image>> future =
  Executors.newSingleThreadExecutor().submit(new Callable<Set<Image>>()
    {
      @Override
      public Set<Image> call() throws Exception
      {
        return someServiceThatLoadsImages.load();
      }
    });

try
{
  Set<Image> images = future.get();
  display(images);
} catch (Exception e)
{
  logger.error("Something bad happened", e);
}
like image 107
Boris Pavlović Avatar answered Sep 23 '22 16:09

Boris Pavlović