0

The questions refers specifically to spawning threads through anonymous inner classes, and not at a class level extending Thread / implementing Runnable. If they are the same please explain why.

Can anyone explain what the difference is between these 2 ways of spawning a new background Thread in Android:

1. With new Runnnable

    Thread backgroundThread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            // Do stuff in background
        }
    });
    backgroundThread1.start();

2. Without new Runnnable

    Thread backgroundThread2 = new Thread() {
        @Override
        public void run() {
            // Do stuff in background
        }
    };
    backgroundThread2.start();
TomV
  • 1,157
  • 1
  • 13
  • 25
  • Yes, lots of good information on implementing Runnable and extending Thread at a class level in that particular page. However, this question specifically refers to anonymous inner classes. If there isn't a difference between spawning anonymous inner class threads and class level threads, please explain why. – TomV Jul 19 '18 at 12:07
  • 1
    The choice of whether to use an anonymous inner class instead of using a named class has no bearing on the question of whether to create a new `Thread` instance with a `Runnable` delegate or whether to override the `Thread#run()` method. – Solomon Slow Jul 19 '18 at 13:51
  • 1
    The only real difference in spawning an anonymous class for threads (in both cases this is true) is that the anonymous class will hold a reference back to your outer class. So that object won't be GC'ed until the thread finishes. However, in Android often with Activites, etc they could be killed by the user while the thread is working, and when it returns trying to update the UI and an error is thrown because you don't first check that the Activity is still active... – chubbsondubs Jul 19 '18 at 15:29
  • 1
    ...Now it's probably not practical to cut that reference because if you had named classes you'd probably still need to pass the reference to the object to notify when it's done. That being said I use Anonymous classes for this exact thing all the time in Android because it gives me an elegant way to update the UI quickly. But I also go the extra step to build an architecture that encapsulates checking the context is still active before I run the UI update portion. Keep in mind that in both cases Runnable vs Thread you showed used anonymous classes so it applies to both. – chubbsondubs Jul 19 '18 at 15:31

0 Answers0