Basic Multithreading
suggest changeIf you have many tasks to run, and those tasks do not depend on the results of the preceding ones, you can use multithreading so the computer can run them at the same time on more than one processor. That can make the program faster when the tasks are large and independent. Printing from many threads is often not faster, because System.out is shared.
class CountAndPrint implements Runnable {
private final String name;
CountAndPrint(String name) {
this.name = name;
}
/** This is what a CountAndPrint will do */
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println(this.name + ": " + i);
}
}
public static void main(String[] args) {
// Launching 4 parallel threads
for (int i = 1; i <= 4; i++) {
// `start` method will call the `run` method
// of CountAndPrint in another thread
new Thread(new CountAndPrint("Instance " + i)).start();
}
// Doing some other work on the main thread
for (int i = 0; i < 10000; i++) {
System.out.println("Main: " + i);
}
}
}
The run methods of the CountAndPrint instances execute in an unpredictable order. The loops start at 0. A snippet of one run might look like this:
Instance 4: 1
Instance 2: 1
Instance 4: 2
Instance 1: 1
Instance 1: 2
Main: 1
Instance 4: 3
Main: 2
Instance 3: 1
Instance 4: 4
...
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents