In this day and age programmers must implement multi-threading solutions into their code. Every somewhat modern programming language that respects itself offers opportunities to work with threads. Today we’re going to learn how to do this in Java. This article requires at least a little knowledge of Java such as classes, objects, inheritance and interfaces. We’ll try to keep it simple.
Before we jump into the middle of everything, we must learn the basics so that we won't get lost during the coding process later on. First of all, a thread is a single sequential flow of control-each thread within a program becomes its own thread of execution. This is how an application can execute multiple threads concurrently. The most critical advantage of doing so is maximizing CPU power and throughput.
The simplest way to imagine two threads is to consider the following mathematical equation: 2 + 5 + 9 + 3. It's simple, right? We promised to keep it simple. Jokes aside, the entire equation is composed of three addition operations. The sequential solution involves one solo thread calculating 2 + 5 = 7, then adding 9 to this, which gives 16, and ultimately adding 3. The end result is 19.
Now please bear with me but let's imagine that one addition takes one second (I know, I know!). This is not a computer at work; let's imagine that it's a six-year old kid practicing math. The entire process took three whole seconds until the kid shouted out the final answer (hence 2 + 5 = 7; 7 + 9 = 16; 16 + 3 = 19). Now what would happen if we brought in another pupil and tried to make them cooperate?
While the first kid calculates 2 + 5, the second kid calculates 9+3. Assuming that both of them require equally one second to calculate, this means both results are calculated in the first second. Now the first kid finally adds those two results and finds out that 7 + 12 is 19. This addition once again took another second. But hey! The entire calculation process took a total of two seconds. It ran 33 percent faster than the original process!
The above analogy might seem silly and long-winded, but that's actually one of the simplest ways to imagine multi-threading. Of course, computers can work with bigger numbers and under shorter time periods, but the bottom line is still the same. Now that we know what this is about, let's fire up our favorite Java IDE and begin coding.