by BehindJava

How to create and run multiple threads using for loop

Home » java » How to create and run multiple threads using for loop

In this tutorial we are going to make our task easy by creating multiple threads using a for loop as shown in the below code.

Here, We are creating 5 threads that are running parallelly and if you want increase the creation of number of threads, you can simply change the number in for loop present the main method as per your requirement.

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[]) {
		for (int i = 0; i <= 5; i++) {
			Counter c1 = new Counter();
			c1.start();
		}
	}

}

Output:

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

Note: 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.