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

  1. nice article. thanks for sharing such nice post . visit java collection tutorial

    ReplyDelete
  2. Amazing blog got vey information about java from this blog thanks for sharing with us
    Angular course
    Angular training

    ReplyDelete

Post a Comment

Popular posts from this blog

Java Collection Framework - In 15 Mins

Collection framework is use for storing data in program. Collection framework contains most of data structure like LinkedList, Set, HashMap etc already implemented for you to direct use in program and also gives you flexibility to write own kind of data structure. Java collections framework data structure: Lists: Contains list of objects. Java provides 3 type of ready to use list. ArrayList Vector LinkedList Sets: Contains unique objects, does not allow dublicates. Java provides 3 type of sets, these are HashSet LinkedHashSet TreeSet Maps: Contain key:value data structure, value only access by key. Java provides 4 type of Map. HashMap Hashtable LinkedHashMap TreeMap Queues: Perform FIFO (first in first out) PriorityQueue Java Collection Interface And Collections Util Class Collection is an interface which is implemented by all data structure in java, except Map. Maps (HashMap, LinkedHashMap, Hashtable, TreeMap) are not define by Collection interface, th...

String - A story of very special class in java

String is most used java class in any java project. Java treated String as special class. Lets see, what so special in String. String Basics String is group of characters. char[] chrs = {'i',' ','a','m',' ','h','e','r','o','.'}; String str = new String(chrs); System.out.println(str); /* Output: i am hero. */ String is an immutable class. Immutable class:  A java class which object can not be modified if once created. Because String class is immutable, String is final in nature, its mean you can not modify string object once you created. Default value of string is null. Simplest way to initialize String is //object created in String Literal Pool String str = "hello world"; Above example known as String literal, All string literals in Java programs, such as "hello world", are object of String class. Another way to create String object is //object created in Heap m...

What is Java Serialization?

Java has classes, A class has properties. These properties with values called object or state of object. Now we want to save this state of object into file or database. With java serialization we can convert object state into data stream and this data stream would be save into file system or database or create object replica into another system. Java Serialization Covered Two Process - Serialization : Convert object state into data stream. Deserialization : Convert data stream into object state.  Simple Java Code Example:  import java.io.Serializable; public class Student implements Serializable{ private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public void print() { System.out.println("Name:"+name+" Age:"+age); } } import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputS...