Friday, October 10, 2014

Java Threads : simple introduction

Recently I was asked about the usage of threads in Java :
1- how to create them.
2- the difference between run() and start() methods.

first : how to create them.
I will talk about simply creating one thread at a time then starting it- there are ways to create thread pools then using or creating threads to be run at a later time which I will not mention.
you can create threads by:

a- creating a subclass of the Thread class:
    a1-  creating a subclass of the Thread class
    a2-  overriding the run() method to execute your code that you want to be run inside a different thread. 
    a3- create a new instance of your thread subclass
    a4- call the start() method of the new instance

b- creating a new class that implements Runnable interface
    b1-creating a new class that implements Runnable interface
    b2- provide an implementation for the run() method that will execute your code
    b3- create a new Thread instance and pass it an instance of your subclass that implements the        Runnable interface
    b4- call the start() method of the thread instance.


both will run your code inside a separate thread. But if you extend the Thread class then you fixed Thread as the parent of the class and since in Java you have only one parent class then it will restrict your code.
but if you implement the Runnable interface then you won't face this issue.



another question I was asked was the difference between calling the run() and the start() methods on the thread instances?
- calling run(): 
   1- will call the method and it will execute in the current thread
   2- you can call it multiple times on the same thread without problems.
  ==> the same as calling a method on any class

- calling start():
 1- will start the thread life cycle, it will go from New to RUNNABLE and eventually to 
      TERMINATED, and the run() method will be called which will execute your code
 2- your code will be executed in a different thread.
 3- if you call more than one time you will get an exception every time after the first one

No comments:

Post a Comment