Advanced Java Programming - Old Questions

Question Answer Details

1. What is multithreading? How can you write multithreaded programs in java? Discuss with suitable example.

10 marks
Asked in 2073

Answer

AI Generated Answer

AI is thinking...

Official Answer

Multithreading is a process of executing two or more threads simultaneously to maximum utilization of CPU A thread is a lightweight sub-process, the smallest unit of processing.

Multithreaded program can be created by using two mechanisms:

1. By extending Thread class

Thread class provide constructors and methods to create and perform operations on a thread. 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.

Example:

class First extends Thread

{

    @Override

    public void run()

    {

        for (int i=1; i<=10; i++)

        {

            System.out.println(i);

            try

            {

                Thread.sleep(500);

            }

            catch (InterruptedException e)

            {

                System.out.println(e.getMessage());

            }

        }

 

    }

}

class Second extends Thread

{

    @Override

    public void run()

    {

        for (int i=11; i<=20; i++)

        {

            System.out.println(i);

            try{

                Thread.sleep(1000);

            }

            catch (InterruptedException e)

            {

                System.out.println(e.getMessage());

 

            }

        }

    }

}

public class ThreadInterval

{

    public static void main(String[] args)

    {

        Thread first = new First();

        Thread second= new Second();

        first.start();

        second.start();

    }

}


2. By implementing Runnable interface

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run() which  is used to perform action for a thread. The start() method of Thread class is used to start a newly created thread.

Example:

public class ExampleClass implements Runnable {  

    @Override  

    public void run() {  

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

    }  

    public static void main(String[] args) {  

        ExampleClass ex = new ExampleClass();  

        Thread t1= new Thread(ex);  

        t1.start();  

        System.out.println("Hi");  

    }  

}