Thursday 5 May 2022

Question:- Write a program in Java to demonstrate the concept of multithreading using Runnable interface.

 Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

जावा के इस फीचर से हम प्रोग्राम के एक से ज्‍यादा पार्टस को एक साथ रन कर सकते हैं जिससे सीपीयू का अधिकतम उपयोग किया जा सके। इन पार्टस को थ्रेड कहा जाता है। तो थ्रेड भी एक प्रोसेस के अन्‍दर लाइटवेट प्रोसेसेज होती है।



Threads can be created by using two mechanisms : 

थ्रेड को दो प्रकार से बनाया जा सकता है।

1. By Implementing the Runnable Interface (Runnable Interface का इस्‍तेमाल/लागू करके)

We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.

इसमें रनेवल इन्‍टरफेस को इम्‍प्‍लीमेंट कर नयी क्‍लास बनायी जाती है और रन मेथेड को पुन: लिखा जाता है। उसके बाद थ्रेड का ऑब्‍जेक्‍ट बनाकर स्‍टार्ट मेथेड को कॉल किया जाता है।


// Java code for thread creation by implementing

// the Runnable Interface

class MultithreadingDemo implements Runnable {

public void run()

{

System.out.println("Thread has ended");

}

}


// Main Class

class Multithread {

public static void main(String[] args)

{

MultithreadingDemo ex = new MultithreadingDemo();

Thread t1= new Thread(ex);

t1.start();

System.out.println("Hi");  

}

}


Output:-

Hi

Thread has ended

-----------------------------------------------------------------------------------------------------------------------------

2. By Extending the Thread class  (Thread Class का विस्‍तार करके )

We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.

इस तरीके में Thread क्‍लास का विस्‍तार करके एक नयी क्‍लास बनायी जाती है। इस नयी क्‍लास में थ्रेड क्‍लास के रन मै‍थेड की आवश्‍यकतानुसार पुन: कोडिंग(Overriding) की जाती है। एक थ्रेड का कार्य रन मैथेड के अन्‍दर ही निहित होता है। अब  जो नयी क्‍लास बनायी है उसका ऑजेक्‍ट बनाते हैं और थ्रेड का एक्‍जीक्‍यूशन चालू करने के लिए स्‍टार्ट मैथक को कॉल करते हैं। थ्रेड का स्‍टार्ट मैथड, रन मैथड में निहित कोडिग को एक्‍जीक्‍यूट करता है।

class MultithreadingDemo extends Thread{  

  public void run(){  

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

  }   

}

// Main Class

class Multithread {

  public static void main(String args[]){  

     MultithreadingDemo obj=new MultithreadingDemo();   

     obj.start();  

  }  

}


Output:

My thread is in running state.


No comments:

Post a Comment