Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

difference between start() and run()  RSS feed

 
radhika ayirala
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

What is the difference between t.start() and t.run().

MyThread t = new MyThread();
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you checked out the Java Tutorial on Threads? It starts here.

Basically, you can think of the thread as a worker that will do a task for you. The run() method is a list of instructions that you give the worker (before they start doing it). The start() method is your command that says "now, start doing it!". When you create a thread, you call the start() command yourself, but you don't call the run() command. (You could, but it's pointless.) Instead, after you call start, the thread calls run() on its own.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
start() does a lot of deep magic, setting up a new thread in the OS (in most modern JVMs), establishing a new stack, etc. One of the nice things about OO design is that Sun was able to completely change start() from using JVM managed threads to OS managed threads and we never had to even know about it.

As Jim said, start() eventually calls run() on the new thread. There's no magic in run(), unless it's you that puts it there.
 
paritosh ranjan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you say t.start() a new thread with its own stack is started.the run method of the thread is called but the code of the run method runs in a newly created thread.

when you say t.run() no new thread is created.the code inside the run method executes but the code uses the same stack which was used by the thread in which t.run() was written.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!