Interview Questions

How to implement Threads in java?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

3. How to implement Threads in java?

This is very basic threading question. Threads can be created in two ways i.e. by implementing java.lang.Runnable interface or extending java.lang.Thread class and then extending run method.

Thread has its own variables and methods, it lives and dies on the heap. But a thread of execution is an individual process that has its own call stack. Thread are lightweight process in java.

1. Thread creation by implementing java.lang.Runnable interface.
We will create object of class which implements Runnable interface :
MyRunnable runnable=new MyRunnable();
Thread thread=new Thread(runnable);
2) And then create Thread object by calling constructor and passing reference of Runnable interface i.e. runnable
Thread thread=new Thread(runnable);

(Continued on next question...)

Other Interview Questions