Java – Multithreading

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 a program is called a thread.

Multitasking is when multiple processes share common processing resources such as a CPU. Each of the threads can run in parallel. The OS divides processing time not only among different applications but also among each thread within an application.

Threads can be created by using two mechanisms:

  • Extending the Thread class
  • Implementing the Runnable Interface

Thread creation by extending the 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. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.

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 creation by implementing the 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. If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface.

class RunnableDemo implements Runnable {
   private Thread t;
   private String threadName;
   
   RunnableDemo( String name) {
      threadName = name;
      System.out.println("Creating " +  threadName );
   }
   
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 2; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // Let the thread sleep for a while.
            Thread.sleep(30);
         }
      }catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }
   
   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

public class TestThread {

   public static void main(String args[]) {
      RunnableDemo R1 = new RunnableDemo( "Thread-1");
      R1.start();
      
      RunnableDemo R2 = new RunnableDemo( "Thread-2");
      R2.start();
   }   
}

Thread Methods

Following is the list of important methods available in the Thread class.

  • public void start() – Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
  • public void run() – If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
  • public final void setName(String name) – Changes the name of the Thread object. There is also a getName() method for retrieving the name.
  • public final void setPriority(int priority) – Sets the priority of this Thread object. The possible values are between 1 and 10.
  • public final void setDaemon(boolean on) – A parameter of true denotes this Thread as a daemon thread.
  • public final void join(long millisec) – The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
  • public void interrupt() – Interrupts this thread, causing it to continue execution if it was blocked for any reason.
  • public final boolean isAlive() – Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.
Related Post