What is Thread – Definition, Applications, Multithreading in Java Tutorial

What is Thread – Definition, Applications, Multithreading in Java Tutorial

What is Thread – Definition, Applications, Multithreading Tutorial – Threads are a way for a program to split itself into two or more parallel running tasks.

 

What is thread

Threads are a lightweight process. Thread consumes fewer system resources as compared with processes.

 

Thread definition 1

Thread is a mechanism that allows an application to perform multiple tasks concurrently.

 

Thread definition 2

A thread can be also defined as a set of processes that shares the same memory space and other attributes during the execution.

 

Thread definition 3

A thread is a sequence of instructions within a program that can be executed independently of other codes.

 

What is a multi-threaded programming

Multithreading in java is similar to multitasking. Multithreading in java enables the processing of multiple threads at the same time, rather than multiple processes.

A multithreaded operating system runs several background tasks at one time such as logging file changes, indexing data, and managing windows and other tasks at the same time.

The main aim of multithreading in java is to provide simultaneous execution of two or more parts of a program in order to maximize the use of the processor.

A multithreaded program contains two or more parts that can run in parallel. Each such part of the program is called a thread.

The following figure shows how Multithreading in java works –

What are the threads in a processor

Threads refer to lightweight processes executed by a processor. Using many threads at a time Process can handle many tasks at the same time that not only improve the efficiency of a task but also maximize the utilization of the processor.

 

Thread computing

Creating Threads

Threads are created in the form of objects that are executed with the help of run() method. To run thread import java.lang.Thread class.

 

Multithreading in java – thread tutorial

//Thread creation by extending Thread class

class MultithreadingDemo extends Thread

{

 public void run()

{

 System.out.println(“My thread is in running state.”);

 }

 public static void main(String args[])

{

 MultithreadingDemo obj=new MultithreadingDemo(); obj.start();

 }

 }

 

Output:-

My thread is in running state.

 

Example 2

// Program for Multithreading to print two lists 1. List to print natural numbers 2. List to print even numbers and 3. List of odd numbers.

 

class A extends Thread

{

Public void run()

{

For(int i=1; i<=5; i++)

{

System.out.println(“ Thread A natural number “+i);

}

System.out.println(“end of thread A: List of natural numbers”);

}

 

Class B extends Thread

{

Public void run()

{

For(int j=0; j<=5; j=j+2)

{

System.out.println(“ Thread B even number “+j);

}

System.out.println(“end of thread B: List of even numbers”);

}

Class C extends Thread

{

Public void run()

{

For(int k=1; k<=5; k=k+2)

{

System.out.println(“ Thread C odd number “+k);

}

System.out.println(“end of thread C: List of odd numbers”);

}

}

 

class ThreadTest

{

Public static void main(String arg[])

{

new A().start();

new B().start();

new C().start();

}

}

 

Output

Thread A natural number 1

Thread A natural number 2

Thread A natural number 3

Thread A natural number 4

Thread A natural number 5

end of thread A: List of natural number

Thread B even number 2

Thread B even number 4

Thread B even number 6

Thread B even number 8

Thread B even number 10

end of thread B: List of even numbers

Thread C odd number 1

Thread C odd number 3

Thread C odd number 5

Thread C odd number 7

Thread C odd number 9

end of thread C: List of odd numbers

 

Multithreading in java – Thread States: Life Cycle of a Thread

During the life cycle of a thread, it enters in various states as given below-

  • Born state or newborn state
  • Ready state or Runnable state
  • Running state
  • Blocked state
  • Dead state

 

  • Born state
    • This is the state when a Thread just created
    • When a thread start called ready state
  • Ready state (runnable state)
    • A highest priority ready thread enters the running state
  • Running state
    • The system assigns processor to a thread and the thread begins running
    • When run completes or terminates, the thread enters into a dead state
  • Dead state
    • Thread marked to be removed by the system
    • The thread Entered when run terminates or throws an uncaught exception
  • Blocked state
    • The thread Entered from the running state
    • A blocked thread cannot use a processor, even if available
    • The common reason for a blocked state is waiting on I/O request
  • Sleeping state
    • The thread Entered when sleep method called
    • In this state, the thread cannot use processor
    • The thread enters the ready state after sleep time expires
  • Waiting state
    • The thread entered when wait called in an object thread is accessing
    • One waiting thread becomes ready when object calls notify
    • When notifyAll – all waiting threads become ready

 

Thread Priorities and Scheduling

In java, each thread is assigned a priority. Priorities affect the order in which the threads are executed. Threads have priority from 1 to 10

  • MIN_PRIORITY – 1
  • NORM_PRIORITY – 5 (default)
  • MAX_PRIORITY – 10
  • New threads inherit the priority of the thread that created it

Each thread is assigned a predefined time called Timeslicing. Each thread gets a quantum of processor time to execute. After the time is up, the processor is given to the next thread of equal priority if other threads are available).

To set a Priority of a thread following methods are used-

Priority methods:-

  • setPriority( int priorityNumber )
  • getPriority
  • yield – thread yields processor to threads of equal priority

 

 

Runnable Interface

The simplest way to create a thread is to create a class implementing the Runnable interface. To execute run() method by a thread, pass an object of the to the Thread in its constructor.

 

We can create threads using two methods-

  • Using Thread class
  • Using Runnable Interface

 

Use the following steps to implement threads with Runnable Interface:-

  • Declare a class implementing Runnable interface
  • Implement run() method
  • Declare an object of the runnable class as the target of the thread
  • Call start() method to run the thread

 

Tutorial of Runnable Interface

// Display five natural numbers using Runnable Interface

class T implements Runnable

{

Public void run()

{

For(int i=1;i<=5;i++)

{

System.out.println(“Thread T”+i);

}

System.out.println(“End of Thread T”);

}

}

class Ttest

{

public static void main(String arg[])

{

T runnable = new T();

Thread x = new Thread(runnable);

x.start();

System.out.println(“End of main Thread”);

}

}

 

Output:

Thread T 1

Thread T 2

Thread T 3

Thread T 4

Thread T 5

End of Thread T

 

Question for Practice

Write a program using Thread to display two threads as given below-

  1. List of five prime numbers
  2. List of five random numbers

Write a program using Runnable Interface to display a factorial of n. n=5

Thanks for reading, Welcome to your comments on this Post

This site uses Akismet to reduce spam. Learn how your comment data is processed.