Core Java >> MultiThreading


Ways for Thread Instantiation



A thread can be created in multiple ways in Java. Two of them have been discussed in earlier blog post which included either using the Thread class or using the Runnable interface. But here I will discuss how to create threads from single object and creating threads from multiple objects and the difference between the two.

The way we create thread also determines how the locking should be done when synchronizing a method or a block of code.

Creating Threads from single object

package com.example;

public class Test implements Runnable{

    public void run(){
         System.out.println("Inside run method");
    }

    public static void main(String args[]){
        System.out.println("Inside Main");
        Test t1 = new Test();
        Thread a1 = new Thread(t1);
        Thread a2 = new Thread(t1);

        a1.start();
        a2.start();

        System.out.println("Exiting main");
    }
}

Output:
Inside Main
Inside run method
Exiting main
Inside run method

Here we can see the same object t1 is being used to create the two thread objects a1 and a2. The output shows that two threads have run. The locking level associated with this kind of instantiation is known as instance level locking because we are using a single instance of Test class to create multiple threads.


Creating threads from multiple objects

package com.example;

public class Test implements Runnable{

    public void run(){
         System.out.println("Inside run method");
    }

    public static void main(String args[]){
        System.out.println("Inside Main");
        Test t1 = new Test();
        Test t2 = new Test();
        Thread a1 = new Thread(t1);
        Thread a2 = new Thread(t2);

        a1.start();
        a2.start();

        System.out.println("Exiting main");
    }
}

Output:
Inside Main
Inside run method
Exiting main
Inside run method

Here as you can see that we have created two objects of class Test and then created two threads using those two objects t1 and t2. The locking level associated with this kind of thread creation is known as class level locking.

The difference between the above two approaches will become clear in my post about class level locking and instance level locking.

Stay Tuned!!

Multi-Threading Tutorials
Best Books for Multi-Threading in Java
Introduction to Multi-Threading
Java Thread Overview

Leave Comment