Multithreading in java:

              Thread is a light weight process which is of simple set of operations to execute. It promotes the concurrent execution and increases CPU utilization. It can be implemented by two ways in java.

  1. ·       Implementing Runnable interface.
  2. ·       Extending the Thread class

Let us implement the multithreading in java..

1.How to create threads by implementing Runnable interface?

              This can be achieved by following the steps given below.

Steps:

  • ·       Create a class which implements java.lang.Runnable builtin class.
  • ·       Next, override the run () method.
  • ·       Use the constructor to instantiate the thread object.
  • ·       At last, call the start () method of thread object.

class MultithreadingSample implements Runnable {

public void run() {

try {

System.out.println("User Thread " + Thread.currentThread().getId() + " is running");

} catch (Exception e) {

System.out.println("Exception is found");

}

}

}

public class MultithreadingEg1 {

public static void main(String[] args) {

int x = 6; // No of threads

for (int i = 0; i < x; i++) {

Thread obj = new Thread(new MultithreadingSample());

obj.start();

}

}

}

Output:

C:\raji\blog>javac MultithreadingEg1.java

C:\raji\blog>java MultithreadingEg1

User Thread 22 is running

User Thread 26 is running

User Thread 21 is running

User Thread 24 is running

User Thread 23 is running

User Thread 25 is running

2. How to implement thread by Extending the Thread class:

              These are the steps to follow.

Steps:

  • ·       Create a class which implements java.lang.Thread.
  • ·       Next, override the run() method.
  • ·       The run() method constitutes the thread.
  • ·       At last, call the start () method which itself calls the run() method.

Program:

class MultithreadingSample1 extends Thread {

public void run() {

try {

System.out.println(" The Thread " + Thread.currentThread().getId() + " is running");

} catch (Exception e) {

System.out.println("Exception is found");

}

}

}

 public class MultithreadingEg2 {

public static void main(String[] args) {

int x = 6;

for (int i = 0; i < x; i++) {

MultithreadingSample1 obj = new MultithreadingSample1();

obj.start();

}

}

}

Output:

C:\raji\blog>javac MultithreadingEg2.java

C:\raji\blog>java MultithreadingEg2

 The Thread 23 is running

 The Thread 25 is running

 The Thread 24 is running

 The Thread 26 is running

 The Thread 22 is running

 The Thread 21 is running

Advantages of Multithreading:

Multithreading offers multiple advantages listed below.

Efficient: Multiple threads run at same time. It increases the efficiency.

Fault tolerance: It does not affect the one thread’s fault to another.

Concurrency: Multiple threads are running at a same time.

These are ways to implement multithreading in java. keep coding....

No comments:

Post a Comment