Java-Multithreading

Multithreading

Multithreading is a conceptual programming paradigm where a program is divided into two or more subprograms, which can be implemented at the same time in parallel. For example, one subprogram can display an animation on the screen while another may build the next animation to be displayed. This is something similar to dividing a task into subtasks and assigning them to different people for execution independently and simultaneously.

In most of our computers, we have only a single processor and therefore, in reality, the processor is doing only one thing at a time. However, the processor switches between the processes so fast that it appears to human beings that all of them are being done simultaneously. Java programs that we have seen and discussed so far contain only a single sequential flow of control. This is what happens when we execute a normal program. The program begins, runs through a sequence of executions, and finally ends. At any given point of time, there is only one statement under execution.

A thread is similar to a program that has a body, and an end, and executing commends sequentially. In fact, all main programs in our previous examples can be called single thread programs. Every program will have at least one thread. A unique property of Java is its support for multithreading. That is, Java enables us to multiple flows of control in developing programs. Each flows of control may be thought of as a separate tiny program known as a thread that runs in parallel to others. A program that contains multiple flows of control is known as multithreaded program.

It is important to remember that ‘threads running in parallel’ does not really mean that they actually run at the same time. Since all the threads are running on a single processor, the flow of execution is shared between the threads. The Java interpreter handles the switching of control between the threads in such a way that it appears they are running concurrently. Multithreading is a powerful programming tool that makes Java distinctly different from its fellow programming languages. Multithreading is useful in a number of ways. It enables programmers to do multiple things at one time. They can divide a long program (containing operations that are conceptually concurrent) into threads and execute them in parallel. Any application we are working on that requires two or more things to be done at the same time is probably a best one for use of threads.

Creating Threads

Creating threads in Java is simple. Threads are implemented in the form of objects that contain a method called run( ). The run( ) method is the heart and soul of any thread. It makes up the entire body of a thread and is the only method in which the thread’s behaviour can be implemented. A typical run( ) would appear as follows:


The run( ) method should be invoked by an object of the concerned thread. This can be achieved by creating the thread and initiating it with the help of another thread method called start( ). A new thread can be created in two ways.

1) Extending Thread Class Define a class that extends Thread class and override its run( ) method with the code required by the thread.
2) Implementing Runnable Interface Define a class that implements Runnable interface. The Runnable interface has only one method, run( ), that is to be defined in the method with the code to be executed by the thread.

The approach to be used depends on what the class we are creating requires. If it requires to extend another class, then we have no choice but to implement the Runnable interface, since Java classes cannot have two superclasses.

Extending Thread Class

We can make our class runnable as thread by extending the class Thread, and then to create an instance of that class. The extending class must overwrite the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread.

The following program illustrates the use of Thread class for creating and running threads in an application. The program creates two threads th1 and th2 for undertaking two different tasks. The main method in the Javaapp class also constitutes another thread which we may call the “main thread”. The main thread dies at the end of its main method. However, before it dies, it creates and starts the two threads th1 and th2. Immediately after the thread th1 is started, there will be two threads running in the program: the main thread and the thread th1. The th1.start( ) method returns back to the main thread immediately after invoking the run( ) method, thus allowing the main thread to start the thread th2. There are a total of three separate threads running in parallel.

We have simply initiated two new threads and started them. We did not hold on to them any further. They are running concurrently on their own. Note that the output from the threads are not specially sequential. They do not follow any specific order. They are running independently of one another and each executes whenever it has a chance. Remember, once the threads are started, we cannot decide with certainly the order in which they may execute statements.

The sleep( ) method is used to suspend a thread for a period of milliseconds. Note that the call to sleep( ) method is enclosed in a try block and followed by a catch block. This is necessary because the sleep( ) method throws an exception, which should be caught. If we fail to catch the exception, program will not compile.

Program

sdsdsrrt


Program Source

class ThreadOne extends Thread {
    
    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            try {
                Thread.sleep(1000);
            }catch(InterruptedException ex)
            {
                System.out.println("ThreadOne Interrupted");
            }
            System.out.println("ThreadOne  : "+i);
        }
        System.out.println("Exiting ThreadOne");
    }
}

class ThreadTwo extends Thread {
    
    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            try {
                Thread.sleep(1000);
            }catch(InterruptedException ex)
            {
                System.out.println("ThreadTwo Interrupted");
            }
            System.out.println("ThreadTwo  : "+i);
        }
        System.out.println("Exiting ThreadTwo");
    }
}

public class Javaapp {
    
    public static void main(String[] args) {
        
        ThreadOne th1 = new ThreadOne();
        th1.start();
        
        ThreadTwo th2 = new ThreadTwo();
        th2.start();
         
        for(int i=1;i<=5;i++)
        {
            try {
                Thread.sleep(1000);
            }catch(InterruptedException ex)
            {
                System.out.println("ThreadMain Interrupted");
            }
            System.out.println("ThreadMain : "+i);
        }
        System.out.println("Exiting MainThread");
    }
}

Leave a Comment