***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***

posts

    Multithreading in Java

    A thread in Java is a lightweight process requiring fewer resources to create and shares the process resources.

    A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

    Threads use a shared memory area which helps to save memory, and also, the content-switching between the threads is a bit faster than the process.

    In Java, Multithreading refers to a process of executing two or more threads simultaneously for maximum utilization of the CPU.

    Advantages of Multithreading are:

    • Multithreading saves time as you can perform multiple operations together.
    • The threads are independent, so it does not block the user to perform multiple operations at the same time and also, if an exception occurs in a single thread, it does not affect other threads.

    There are two ways to create a thread:

    1. By extending Thread class
    2. By implementing Runnable interface.

    The first is to create a subclass of Thread and override the run() method. The second method is to pass an object that implements Runnable (java.lang.Runnable) to the Thread constructor.

    Thread class:

    Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.

    The first is to create a subclass of Thread and override the run() method. The run() method is executed by the thread start() call is made.

     

    Ex:

    public class Mythread extends Thread {

      public static void main(String[] args) {

        Mythread thread = new Mythread();

        thread.start();

        System.out.println("This code is outside of the thread");

      }

      public void run() {

        System.out.println("This code is running in a thread");

      }

    }

    Runnable Interface Implementation:

    A Java object that implements the Runnable interface can be executed by a Java Thread. The Runnable interface is a standard Java Interface that comes with the Java platform. The Runnable interface only has a single method run().

    Whatever the thread is supposed to do must be included in the implementation of the run() method.

    If the class implements the Runnable interface, the thread can be run by passing an instance of the class to a Thread object's constructor and then calling the thread's start() method

    Ex:

    public class Mythrea implements Runnable {

      public static void main(String[] args) {

        Mythread obj = new Mythread();

        Thread thread = new Thread(obj);

        thread.start();

        System.out.println("This code is outside of the thread");

      }

      public void run() {

        System.out.println("This code is running in a thread");

      }

    }

    No comments:

    Post a Comment