Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are methods called from a separate thread, run on the calling thread?

I've been using threads for 2-3 days now, and I've got a quick question regarding methods. I'm making an Android application and it starts off with the main UI thread (let's call it the "UI Thread" for clarity). I'm spawning a new thread using the following code:

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        someMethod();
    }

});
thread.start();

My question is, will someMethod() also run on the new thread that I just created because I'm calling it from there? Or will it run on the UI thread? For reference, someMethod() is located outside outside of the method that's creating the new thread.

If someMethod() won't run on the new thread, how do I make it do so? Thanks.

like image 226
NewGradDev Avatar asked Jan 12 '23 10:01

NewGradDev


2 Answers

will someMethod() also run on the new thread that I just created because I'm calling it from there?

Yes, that is exactly what happens. The method is just code. It's independent of the thread-of-control that happens to be running in it at a given point and time. This also means that there could be multiple threads executing that code at any given point in time if there are multiple cpu/cores.

like image 98
Bill Avatar answered Jan 20 '23 10:01

Bill


You should take a look at Callable<V> and Future<T>, there you can call methods, that are not processed on the calling thread. You shouldn't work with threads anyway nowadays. There are more modern approaches available.

Here is a link that should give you an idea http://www.vogella.com/articles/JavaConcurrency/article.html#futures

like image 45
mike Avatar answered Jan 20 '23 10:01

mike