superuserdo
superuserdo

Reputation: 1657

Are methods included in a Thread?

What I mean by this question is if I have a thread that runs some code and that code uses a method that isnt in a thread, is that method also ran in the same thread. Here is a code example of what I am talking about. This is an example using android but Im guessing the same applies for java.

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //Logic

                        randomMethod();
                    }
                }).start();

Then a random method:

    public void randomMethod()
{
    //This method is not wrapped in a thread.
}

So is the randomMethod() ran with the thread that it was called on or is it a separate thread?

Upvotes: 1

Views: 74

Answers (3)

Solomon Slow
Solomon Slow

Reputation: 27115

The word "thread" has two meanings in Java: A thread (little t) is a path of execution through your code. Thread (big T) is a Java standard library class with methods that can be used to create and manage little-t threads.

Methods belong to classes. The methods that belong to the Thread class (not counting its private methods) are exactly those methods that are described in the javadoc for that class: http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

Little-t threads call methods, but they do not own them. Any (little-t) thread in your program can, in principle, call any method in your program. Whether or not it actually does depends entirely on you.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

Methods run in the context of the caller. You can always check your thread id(s) with Thread#currentThread(), for example

// How to get the current thread id and name
Thread t = Thread.currentThread();
System.out.printf("Thread: %d - %s%n", t.getId(), t.getName());

NOTE: A regular Java application is started on the main thread (with id "1").

Upvotes: 1

Pavel Dudka
Pavel Dudka

Reputation: 20934

What you are referring to is called Anonymous class in Java. In this way Thread instance has access to all methods (even private) inside parent class, so you can call your randomMethod(), but this method will be called within anonymous class context - in your case - in a separate thread

So short answer to your question - yes, method will be run in a separate thread

Upvotes: 0

Related Questions