3

I just started learning java and I ran into a slight road block involving threads. I have a static method that I would like to run in its own thread, is this possible? In python I know it would look something like this: import thread;thread.start_new_thread( my_function, () ); And I know how to use threading with non-static methods by implementing Runnable or extending thread, but this is not what I am trying to do.

2
  • 1
    Implementing Runnable does not mean you can't call a static method from within your Runnable. Just create an anonymous class which implements Runnable and calls the static method in its run method. Commented Dec 20, 2013 at 18:50
  • 1
    I am sorry, I am new to java, could you post an example? Commented Dec 20, 2013 at 18:51

4 Answers 4

9

Have a Thread's run method call the static method:

new Thread(Call::yourStaticMethod).start(); 
Sign up to request clarification or add additional context in comments.

Comments

2

The above would create a Static Method that executes in another Thread:

public static void yourStaticMethod() { new Thread(new Runnable(){ // This happens inside a different Thread }).start(); } 

2 Comments

Wouldn't this create a new Thread each time the static method is invoked?
Actually, this will create a new thread every time when static method will be invoked! Magic word "new" ))
2

You need to create a new Thread.(As far as I understand)

Thread t = new Thread(){ @Override public void run(){ method(); } static void method(){// do stuff } } //finally t.start(); 

You can always make a class inside a method and pass more arguments to the thread.

You dont need to wrap Runnable with Thread. Use whichever you like, it is the same thing!

The fact that the method is static is of little importance here.

If the static method really does only use local variables, no object fields or methods, then it is thread-safe. If it accesses any object fields or methods, it may not be thread-safe, depending on what those fields or methods are used for, in other code.

You can either create a new thread inside of a static method or other stuff. It depends on what you want to do.

Comments

1

If you are using Java 8+, you can also use Java lambda expresions. Like this:

new Thread(()-> MyApp.myStaticMethod()).start(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.