Creating Multiple Threads Together
We can create and run multiple threads together in a program – we just give each thread a new object. Here is an example in which four new threads are created and each one prints out its name once in a half-second (i.e. 500 ms). The following program (MultiThread.java) demonstrates this concept.
MultiThread.java
class CustomThread implements Runnable {
Thread t;
CustomThread(String name) {
t = new Thread(this, name);
System.out.println(t + " started.");
t.start();
}
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println(t + " is running..");
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(t + " ended.");
}
}
public class MultiThread {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + " started.");
CustomThread t1 = new CustomThread("1st");
CustomThread t2 = new CustomThread("2nd");
CustomThread t3 = new CustomThread("3rd");
CustomThread t4 = new CustomThread("4th");
System.out.println(Thread.currentThread().getName() + " ended.");
}
}
Output:
The program shows the following output sequence during runtime.
main started.
Thread[1st,5,main] started.
Thread[2nd,5,main] started.
Thread[3rd,5,main] started.
Thread[1st,5,main] is running..
Thread[4th,5,main] started.
main ended.
Thread[2nd,5,main] is running..
Thread[3rd,5,main] is running..
Thread[4th,5,main] is running..
Thread[4th,5,main] is running..
Thread[1st,5,main] is running..
Thread[2nd,5,main] is running..
Thread[3rd,5,main] is running..
Thread[1st,5,main] is running..
Thread[4th,5,main] is running..
Thread[2nd,5,main] is running..
Thread[3rd,5,main] is running..
Thread[2nd,5,main] is running..
Thread[1st,5,main] is running..
Thread[4th,5,main] is running..
Thread[3rd,5,main] is running..
Thread[1st,5,main] is running..
Thread[2nd,5,main] is running..
Thread[3rd,5,main] is running..
Thread[4th,5,main] is running..
Thread[4th,5,main] ended.
Thread[1st,5,main] ended.
Thread[3rd,5,main] ended.
Thread[2nd,5,main] ended.
Explanation
In this example we don’t have control over threads as we are unable to wait until a thread is done executing before going on with the rest of the program. Especially when four new threads are created and the main thread don’t wait for them to finish executing. To be more precise, as the host thread main must wait for others to finish.
The line “Thread[1st, 5, main]” in the output sequence indicates that:
- the name of the thread is ‘1st‘
- here 5 is the priority means NORM_PRIORITY, which is the default priority
- main denotes Thread group name to which this thread belongs
In the next section, we will try to solve this problem.