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

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

java - what will happen if we directly call run method?

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

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

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...