Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a class "TestRunnable" which overrides run method by implementing Runnable. Running overridden run method, as follow :

TestRunnable nr = new TestRunnable();
Thread t = new Thread(nr);
t.setName("Fred");
t.start();
  • What if i directly call t.run();
  • What happen if we don't call t.start(); ?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
361 views
Welcome To Ask or Share your Answers For Others

1 Answer

The run method is just another method. If you call it directly, then it will execute not in another thread, but in the current thread.

Here's my test TestRunnable:

class TestRunnable implements Runnable
{
   public void run()
   {
      System.out.println("TestRunnable in " + Thread.currentThread().getName());
   }
}

Output if only start is called:

TestRunnable in Fred

Output if only run is called:

TestRunnable in main

If start isn't called, then the Thread created will never run. The main thread will finish and the Thread will be garbage collected.

Output if neither is called: (nothing)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...