Master java skills

Multiple tasks by multiple threads

In this tutorial, we will see how we can assign different tasks to multiple threads and get the job done.

For this example, we will create 3 different Runnable classes and 3 different threads to perform those.

package com.javatrainingschool;

public class RunnableTask1 implements Runnable {
	
	public void run() {
		for(int i=0; i < 3; i++) {
			System.out.println(Thread.currentThread().getName() + " : Value of i = " + i);
		}
	}
}
package com.javatrainingschool;

public class RunnableTask2 implements Runnable {
	
	public void run() {
		for(int i=10; i < 13; i++) {
			System.out.println(Thread.currentThread().getName() + " : Value of i = " + i);
		}
	}
}
package com.javatrainingschool;

public class RunnableTask3 implements Runnable {
	
	public void run() {
		for(int i=20; i < 23; i++) {
			System.out.println(Thread.currentThread().getName() + " : Value of i = " + i);
		}
	}
}

Main class

package com.javatrainingschool;

public class MultipleTasksExample {

	public static void main(String[] args) {
		
		Thread t1 = new Thread(new RunnableTask1());
		Thread t2 = new Thread(new RunnableTask2());
		Thread t3 = new Thread(new RunnableTask3());
		
		t1.start();
		t2.start();
		t3.start();
	}
}
Output :
Thread-1 : Value of i = 10
Thread-2 : Value of i = 20
Thread-2 : Value of i = 21
Thread-0 : Value of i = 0
Thread-2 : Value of i = 22
Thread-1 : Value of i = 11
Thread-0 : Value of i = 1
Thread-1 : Value of i = 12
Thread-0 : Value of i = 2

Joining the threads

In the above output, it is random. It is not sequential. We can make it sequential by the use of join() method. Below is the example showing that

package com.javatrainingschool;

public class MultipleTasksExample {

	public static void main(String[] args) {
		
		Thread t1 = new Thread(new RunnableTask1());
		Thread t2 = new Thread(new RunnableTask2());
		Thread t3 = new Thread(new RunnableTask3());
		
		t1.start();
		try {
			t1.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t2.start();
		try {
			t2.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t3.start();
	}
}
Output :
Thread-0 : Value of i = 0
Thread-0 : Value of i = 1
Thread-0 : Value of i = 2
Thread-1 : Value of i = 10
Thread-1 : Value of i = 11
Thread-1 : Value of i = 12
Thread-2 : Value of i = 20
Thread-2 : Value of i = 21
Thread-2 : Value of i = 22