Java Reference
In-Depth Information
Using Multiple Threads in a Program
Using multiple threads in a Java program is as simple as creating multiple Thread objects and starting them. Java does
not have any upper limit on the number of threads that can be used in a program. It is limited by the operating system
and the memory available to the program. Listing 6-3 uses two threads. Both threads print integers from 1 to 500.
The code prints a newline after each integer. However, the output shows a space after each integer to keep the output
short. Only partial output is shown.
Listing 6-3. Running Multiple Threads in a Program
// MultiPrinterThread.java
package com.jdojo.threads;
public class MultiPrinterThread {
public static void main(String[] args) {
// Create two Thread objects
Thread t1 = new Thread(MultiPrinterThread::print);
Thread t2 = new Thread(MultiPrinterThread::print);
// Start both threads
t1.start();
t2.start();
}
public static void print() {
for (int i = 1; i <= 500; i++) {
System.out.println(i);
}
}
}
1 2 3 4 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 6 7 27 28 8 9 10 11 12 29 30 31 13 14 32 15 16 17 ... 496 497 498
499 500 424 425 ... 492 493 494 495 496 497 498 499 500
You will find some interesting things in the output. Every time you run this program, you may get a different
output. However, the nature of the output on your computer can be compared to the output shown above. Note that in
a very fast machine the output may print 1 to 500 and 1 to 500. However, let's focus the discussion assuming that your
output is like the one shown.
The program created two threads. Each thread prints integers from 1 to 500. It starts the thread t1 first and the
thread t2 second. You might expect that the thread t1 will start first to print integers from 1 to 500, and then the thread
t2 will start to print integers from 1 to 500. However, it is obvious from the output that the program did not run the way
you might have expected.
The start() method of the Thread class returns immediately. That is, when you call the start() method of a
thread, the JVM takes note of your instruction to start the thread. However, it does not start the thread right away. It
has to do some housekeeping before it can really start a thread. When a thread starts, it is up to the operating system
to decide when and how much CPU time is given to that thread to execute its code. Therefore, as soon as the t1.start()
and t2.start() methods return, your program enters the indeterminate realm. That is, both threads will start running;
however, you do not know when they will start running and in what sequence they will run to execute their code. When
you start multiple threads, you do not even know which thread will start running first. Looking at the output, you can
observe that one of the threads started and it got enough CPU time to print integers from 1 to 5 before it was preempted.
 
Search WWH ::




Custom Search