Skip to main content

Java Thread - Let's move to parallel execution.

Assume we have 5 array of integer type and we want to add all numbers of array.
  • 1st way (Sequential Way)
    We can pick array one by one and add all numbers and give the result. In this way only one thread (main thread) will execute the program.
  • 2nd way (Multithreaded Way)
    In Multithreaded way, we can create 5 thread and assign an array to each thread to add all the numbers of array. All 5 thread will run parallel and give result 5 times faster than 1st way.

What is Thread & Multithreading?

A process may contain sub processes which execute parallel and use same resource of main process these sub processes are threads and whole phenomena called Multithreading.


How to implement thread in Java?

Java thread is sub process of process. In java, Thread class use to achieve multithreading in program.

Initialize Thread

There is two way to initialize and run thread in java.
  • By extending Thread class
  • By implementing Runnable interface

By extending Thread class


public class TestThread extends Thread {
 
 @Override
 public void run() {
        System.out.println("Thread Runs--"+Thread.currentThread().getName());
 }
 
 public static void main(String[] args) {
  
  //initialize thread 1 and run
  TestThread t1 = new TestThread();
  t1.start();
  
  //initialize thread 2 and run
  TestThread t2 = new TestThread();
  t2.start();
  
 }

}

/*OUTPUT::
 
Thread Runs--Thread-0
Thread Runs--Thread-1
 
 */

Main Points
  • A thread need a task to execute, task implemented into run method and run method is overridden method of Thread class.
  • TestThread extends Thread so TestThread class is a type of thread. creating TestThread class object means we are also creating a Thread object.
  • start() execute thread in different stack so thread run independently.
  • by calling start() method, thread will execute run method to perform the task.

By implementing Runnable interface

In this way, There is seprate class for thread task. This class implemnts Runnable interface which make it Runnable Class.
  • Creating Runnable Class
    
    public class Task implements Runnable{
    
     @Override
     public void run() {
        System.out.println("Thread Runs--"+Thread.currentThread().getName());
     }
    
    }
    
  • Creating Main Application
    
    public class TestRunnable {
     
     public static void main(String[] args) {
      
      //creating runnable class object
      Task task = new Task();
      
      //creating thread with runnable task
      Thread t1 = new Thread(task);
      
      //start thread
      t1.start();
      
     }
    
    }
    

Comments

Post a Comment