Multithreading in java

Ratings:
(4)
Views: 0
Banner-Img
Share this blog:

Multithreading in java

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.

Example of Multi-thread:

package demotest;
public class GuruMultithread implements Runnable{

    /**
     * @param args
     */
    public static void main(String[] args) {
             Thread guruthread1 = new Thread();
             guruthread1.start();
             Thread guruthread2 = new Thread();
             guruthread2.start();
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub        
    }
}

Life Cycle of a Thread

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread. Multithreading in java

There are various stages in life cycle of thread as shown in above diagram:

  • New: In this phase, the thread is created using class "Thread class".It remains in this state till the program starts the thread. It is also known as born thread.
  • Runnable: In this page, the instance of the thread is invoked with a start method. The thread control is given to scheduler to finish the execution. It depends on the scheduler, whether to run the thread.
  • Running: When the thread starts executing then the state is changed to "running" state. The scheduler selects one thread from the thread pool, and it starts executing in the application.
  • Waiting: This is the state when a thread has to wait. As there are multiple threads running in the application, there is a need for synchronization between threads. Hence, one thread has to wait, till the other thread get executed. Therefore, this state is referred as waiting state.
  • Dead: This is the state when the thread is terminated. The thread is in running state and as soon as it completed processing it is in "dead state".

Threads can be created by using two mechanisms :

  • Extending the Thread class
  • Implementing the Runnable Interface

Extending Thread Class in Java Example

One way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run() method, which is the entry point for the new thread. It must also call start() to begin execution of the new thread. Screenshot_29

class ExtendingThread extends Thread 
     { 
           String s[]={"Welcome","to","Java","Programming","Language"}; 
           public static void main(String args[]) 
              { 
             ExtendingThread t=new ExtendingThread("Extending Thread Class"); 
              } 
                public ExtendingThread (String n) 
                 { 
                    super(n); 
                    start(); 
                } 
                public void run() 
                  { 
                      String name=getName(); 
                      for(int i=0;i<s.length;i++) 
                          { 
                         try 
                          { 
                            sleep(500); 
                          } 
                            catch(Exception e) 
                               { 
                               } 
                                System.out.println(name+":"+s[i]); 
                          } 
                      } 
      }

Implementing the Runnable Interface

The Clock applet displays the current time and updates its display every second. You can scroll the page and perform other tasks while the clock updates. The reason is that the code that updates the clock's display runs within its own thread. The Clock applet uses a technique different from SimpleThread’s for providing the run method for its thread. Instead of subclassing Thread, Clock implements the Runnable interface and therefore implements the run method defined in it. Clock then creates a thread with itself as the Thread’s target. When created in this way, the Thread gets its run method from its target. The code that accomplishes this is highlighted:

import java.awt.Graphics;
import java.util.*;
import java.text.DateFormat;
import java.applet.Applet;

public class Clock extends Applet implements Runnable {
    private Thread clockThread = null;
    public void start() {
        if (clockThread == null) {
            clockThread = new Thread(this, "Clock");
            clockThread.start();
        }
    }
    public void run() {
        Thread myThread = Thread.currentThread();
        while (clockThread == myThread) {
            repaint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //the VM doesn’t want us to sleep anymore,
                //so get back to work
            }
        }
    }
    public void paint(Graphics g) {
        //get the time and convert it to a date
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        //format it and display it
        DateFormat dateFormatter =
				DateFormat.getTimeInstance();
        g.drawString(dateFormatter.format(date), 5, 10);
    }
    //overrides Applet’s stop method, not Thread’s
    public void stop() {
        clockThread = null;
    }
}

Java Supports Multithreading

  • Java's multithreading support is centered around the java.lang.Thread class. The Thread class provides the capability to create objects of class Thread, each with its own separate flow of control. The Thread class encapsulates the data and methods associated with separate threads of execution and allows multithreading to be integrated within the object-oriented framework.
  • Java provides two approaches to creating threads. In the first approach, you create a subclass of class Thread and override the run() method to provide an entry point into the thread's execution. When you create an instance of your Thread subclass, you invoke its start() method to cause the thread to execute as an independent sequence of instructions. The start() method is inherited from the Thread class. It initializes the Thread object using your operating system's multithreading capabilities and invokes the run() method. You learn how to create threads using this approach in the next section.
  • The approach to creating threads identified in the previous paragraph is very simple and straightforward. However, it has the drawback of requiring your Thread objects to be under the Thread class in the class hierarchy. In some cases, as you'll see when you study applets in Part VI, "Programming the Web with Applets and Scripts," this requirement can be somewhat limiting.
  • Java's other approach to creating threads does not limit the location of your Thread objects within the class hierarchy. In this approach, your class implements the java.lang.Runnable interface. The Runnable interface consists of a single method, the run() method, which must be overridden by your class. The run() method provides an entry point into your thread's execution. In order to run an object of your class as an independent thread, you pass it as an argument to a constructor of class Thread. You learn how to create threads using this approach later in this chapter in the section titled "Implementing Runnable."

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:

  • Process-based Multitasking(Multiprocessing)
  • Thread-based Multitasking(Multithreading)

Process-based Multitasking (Multiprocessing)

  • Each process have its own address in memory i.e. each process allocates separate memory area.
  • Process is heavyweight.
  • Cost of communication between the process is high.
  • Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.

Thread-based Multitasking (Multithreading)

  • Threads share the same address space.
  • Thread is lightweight.
  • Cost of communication between the thread is low.

Advantages of Java Multithreading

  • It doesn't block the user because threads are independent and you can perform multiple operations at same time.
  • You can perform many operations together so it saves time.
  • Threads are independent so it doesn't affect other threads if exception occur in a single thread.

For indepth understanding of Java click on

Java Tutorials

Java Virtual Machine

Interface in Java

Exception Handling in Java  

You liked the article?

Like: 0

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox