What are Java Threads ? Ways to implement Java Threads with example.

Thread is an execution of a small set of instructions that are independently managed by the operating system scheduler. A Java support multithreading, which means that a simple program is broken parts and every part, is executed concurrently. The parts are model in such a way that it does not affect the running of other parts. It extends multitasking where the application is subdivided into operations called threads. These threads run parallel to each other. The Operating system schedules the processing times of each thread.
 
  • New: New thread’s life cycle begins in a new state and remains in the state until a program calls run method.
  • Runnable: It is the executing state of the thread. The thread is said to be in runnable state.
  • Waiting: Thread is said to be in waiting state when it waits for other threads’ execution to perform specific task. The Thread can again come into a runnable state when a program calls for it.
  • Timed Waiting: Runnable thread enters the waiting state for specific time interval and then can transition back to the executing state after specified waiting time.
  • Terminated: When the thread task is completed as required, it gets terminated. However, the thread cannot transition back to the runnable state from this state.
Since the threads run parallel to each other, the priority of threads have to be set by Operating System to determine order of thread execution. Thread priorities is in range between one (MIN_PRIORITY) to ten (MAX_PRIORITY). By default the thread priority is given by NORM_PRIORITY (value five). The thread with a higher priority is executed first i.e. they are allocated processor first.
 
Threads are created in two ways
  • Runnable Interface
  • Extending Thread Class
Implementing Runnable Interface
 
  • Step 1: First implement the run() method given by the Runnable interface. run() method is the entry point of thread and complete logic is placed inside this function.public void run()
  • Step 2: Instantiate Thread object.Thread(Runnable obj, String threadNam);obj” is the instance of the main class.
  • Step 3: After the creation of a thread object you can call start() method which intern calls the run() method to run the thread.void start()
    Example using Runnable interface

In the main method, the object of the class is created which calls the start method of runnable interface. In the start method a new thread is created and run() method is called for the thread execution.
 
By Extending the Thread Class
 
 

The object is created in the main method of the class and the start method is called. The start method creates a thread and calls the run method for thread execution.
 
 

Leave a Reply

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