by BehindJava

What is MultiThreading and How to create a thread in Java

Home » java » What is MultiThreading and How to create a thread in Java

In this tutorial we are going to learn about implementing the MultiThreading in a Java program.

MultiThreading is the ability to execute multiple different parts of code at the same time or Process of executing two or more threads simultaneously.

Normally in our Java programs, JVM uses only one thread. But we have ability to run multiple threads simultaneously using MultiThreading.

There are two ways of creating a new thread.

  1. A class extends the Thread class

    public class Counter extends Thread {
    
    @Override
    public void run()
    {
    	for(int i=0;i<=5;i++)
    	{
    		System.out.println(i);
    		try {
    			Thread.sleep(1000);
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }
    
    public static void main(String args[])
    {
    	Counter c1=new Counter();
    	Counter c2=new Counter();
    	c1.run();
    	c2.run();
    }
    }

    Output:

    0
    1
    2
    3
    4
    5
    0
    1
    2
    3
    4
    5

    Using c1.run() doest run the run() method in a separate thread, meaning it runs on the existing JVM thread, instead use c1.start() and Java branches off into a new thread and starts running the run method as a separate thread and likewise we can run multiple threads parallelly as shown in the below code which is called multi-threading.

public class Counter extends Thread {

	@Override
	public void run()
	{
		for(int i=0;i<=5;i++)
		{
			System.out.println(i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String args[])
	{
		Counter c1=new Counter();
		Counter c2=new Counter();
		c1.start();
		c2.start();
	}
}

Output:

0
0
1
1
2
2
3
3
4
4
5
5
  1. By implementing the Runnable interface
    While implementing the Runnable interface, your class object would not be treated as a thread object. So you need to explicitly create the Thread class object. We are passing the object of your class that implements Runnable so that your class run() method may execute.

    public class Counter implements Runnable {
    
    @Override
    public void run() {
    	for (int i = 0; i <= 5; i++) {
    		System.out.println(i);
    		try {
    			Thread.sleep(1000);
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }
    
    public static void main(String args[]) {
    	Counter c1 = new Counter();
    	Counter c2 = new Counter();
    	Thread t1 = new Thread(c1);
    	Thread t2 = new Thread(c2);
    	t1.start();
    	t2.start();
    }
    }

    Output:

    0
    0
    1
    1
    2
    2
    3
    3
    4
    4
    5
    5