How to create and start threads in java?

Unlike many other languages it is simple to create and manage threads in java. Your class can gain the concurrent behavior through either extending java.lang.Thread class or implementing java.lang.Runnable interface. Thread class itself implements Runnable interface, due to the same reason compiler will not force the programmer to give an implementation of run() method if the Thread class is extended.

Today we will give you two sample programs. One class extends java.lang.Thread and another one implements java.lang.Runnable. Both implementations give concurrent behavior for your classes, however the second implementation gives you a chance to extend another class. To start a thread we have to use the start() method in Thread class. Since starting a thread differ from one operating system to another, the start() method is implementation is native. If the run() method is directly called on a Thread object, the run() method will be invoked in the same stack and the code will be executed sequentially. start() method will start a new Thread and the started Thread will run concurrently with the starting Thread.

Thread creation through extending Thread class

Thread creation through implementing Runnable interface

Starting a java Thread

Leave a comment

Your email address will not be published. Required fields are marked *