Saturday, April 16, 2016

Java Threading - Three ways to create java threads

In programming, threading is a way of distributing our work. We can delegate a huge load of work in to several threads (i.e several processes). A thread will run as a separate operating system process which can run concurrently with other threads.

There are three ways of creating threads in java

1. Extend the thread class

Thread class has a run method and need override method with the code to run in a its own thread.
To execute code in a separate thread,
  • Instantiate an object of class which is extended by Thread class (Runner)
  • Invoke the start() method of Thread class.
    • start() method will go to Thread class and look for the run method and invoke that in a separate thread.

2. Implement Runnable interface

  • Implement Runnable interface in a class
  • Pass object of that class to a constructor of Thread class.
  • Invoke the start() method 




3. Instantiate a Thread object with a Runnable instance

No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...