The Basics of Multiple Threads in Java

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. 

{mospagebreak title=The Basics and the Thread class} 

A traditional single-threaded application runs into a point where it "takes time" to accomplish a task, and then the entire program halts until that operation is completed, at which time the thread is able to move further. With multi-threading execution, if one thread "takes time," it won’t block the flow of execution of other threads.  

We should also note that if one of the threads modifies a thread-specific variable, then all of the threads will end up "noticing" and working with the new value. Threads are always in one of the following states: running, resumed, ready to run, suspended, or blocked

The first is self-explanatory. The second is a kind of "ready to run" state after being suspended or blocked. A thread in the third state is obviously ready but has not started yet. The fourth state means the thread is temporarily suspended, while a thread in the final state is waiting for something.

Each thread also has a given priority. These are numeric values ranging from 1 to 10. The default priority level is 5 (NORM_PRIORITY constant). A higher priority thread during execution has priority over a lower valued one. The highest priority level, 10, is referred to by the constant MAX_PRIORITY, while the lowest 1 is akin to MIN_PRIORITY. These values are final static int’s (meaning "constants" in everyday coding language). 

Under Java there are two possible ways to create threads. The first route involves doing a simple inheritance from the Thread class. The Thread class can be found inside the java.lang package. Extending this thread with a sub-class means inheriting the parent’s attributes and methods. We are going to cover this a bit later, as well as the other solution, which is implementing the Runnable interface. Moreover, we’ll explain the differences. 

For now let’s stick to the first route. What we’re going to do once the inheritance is done is override the run() method within the sub-class. This is the place where we should actually write the part that tells it "what to do" once launched. Furthermore, we can create an object instance of the sub-class, and right after this we can call the start() method of the aforementioned object that kick-starts the thread. 

class MyThread extends Thread{

private int a;

 

public MyThread(int a){

this.a = a;

}

public void run(){

for (int i = 1; i <= a; ++i){

System.out.println(getName() + " is " + i);

try{

sleep(1000);

}

catch(InterruptedException e){}

}

}

}

 

class MainMyThread{

public static void main(String args[]){

MyThread thr1, thr2;

thr1 = new MyThread(5);

thr2 = new MyThread(10);

thr1.start();

thr2.start();

}

}

The output of the above code snippet is the following. As you can see, the threads are being run simultaneously, so the lines are printed one after another at the same time until the count of five is reached. After that, only the second thread continues. The first thread dies since it has done its work. 

Thread-0 is 1

Thread-1 is 1

Thread-0 is 2

Thread-1 is 2

Thread-0 is 3

Thread-1 is 3

Thread-0 is 4

Thread-1 is 4

Thread-0 is 5

Thread-1 is 5

Thread-1 is 6

Thread-1 is 7

Thread-1 is 8

Thread-1 is 9

Thread-1 is 10

In the code snippet above we have explicitly called the start() method of the two threads. This is one way of doing it. However, some people prefer launching the start() method instantaneously as soon as the object instance is created (basically, a new thread is initialized). You can do this by calling the start() method from the constructor. 

public MyThread(int a){

this.a = a;

start(); // this is the extra line, it starts the threads!

}

On the next page we’re going to tackle the other solution for creating new threads. 

{mospagebreak title=The Runnable Interface} 

On the previous page we learned the first solution to multi-threading; it covered extending the Thread class. The Java programming language does not allow multiple inheritances. This is the major pitfall of this solution. With HTML apps, it is mandatory to extend the Applet class, thus the one and only allowed inheritance is already consumed. So this would mean no chance whatsoever for multi-threading. 

This is why the other solution, which implements the Runnable interface, was designed. The Runnable interface defines only one method, and that’s the run() method. Once again we need to code this method when implementing the Runnable interface. Right after, in order to create multiple threads, we first need to create Runnable object instances, and then we’re going to pass-by-value the objects to the Thread constructor.

Check out the example below. 

class MyRunnable implements Runnable{

private int a;

 

public MyRunnable(int a){

this.a = a;

}

 

public void run(){

for (int i = 1; i <= a; ++i){

System.out.println(Thread.currentThread().getName() + " is " + i);

try{

Thread.sleep(1000);

}

catch (InterruptedException e){}

}

}

}

 

class MainMyThread{

public static void main(String args[]){

MyRunnable thr1, thr2;

thr1 = new MyRunnable(5);

thr2 = new MyRunnable(10);

Thread t1 = new Thread(thr1);

Thread t2 = new Thread(thr2);

t1.start();

t2.start();

}

}

The output will be the same as earlier. 

Thread-0 is 1

Thread-1 is 1

Thread-0 is 2

Thread-1 is 2

Thread-0 is 3

Thread-1 is 3

Thread-0 is 4

Thread-1 is 4

Thread-0 is 5

Thread-1 is 5

Thread-1 is 6

Thread-1 is 7

Thread-1 is 8

Thread-1 is 9

Thread-1 is 10

All right, so this second solution to creating new threads by implementing the Runnable interface is the optimal way to do this when multiple inheritances are required. The earlier solution is a bit easier to use since it doesn’t require that much work. With the Runnable interface implementation we need to declare Thread objects, initialize the Runnable object instances, and call the Thread’s constructor on them. 

Until now we’ve learned that both solutions execute a thread using the start() method. This is critical! Lots of beginners fall into the trap of explicitly calling the run() method of a thread object. This is wrong-it won’t execute the thread as a new one; instead, everything will be processed via the conventional solo-thread approach. 

Therefore, the proper way is to always start a thread using the start() method. At its end, this creates the new thread and right after calls the run() method, just like any other method, but in that newly- created thread. This is the key. Always be careful. 

{mospagebreak title=Taking a Break!} 

We’ve come to the end of this part. By now you should know the basics of the two possible ways of creating and managing threads under Java. Actually, this is barely the tip of the iceberg. Try to research the topic of multi-threading in Java and you’ll surely learn a lot. And don’t forget to practice! Theory without application is null (pun intended). 

This article is going to be followed by a sequel covering a bit more advanced tasks with threads. We’re going to learn how to work with groups of threads, what daemon threads are about, how we can change the states of threads, make them stand by, stop, then resume, and all that-and then, finally, we are going to learn thread synchronization. Synchronization along with locks is really crucial to grasp. 

Moreover, threads can also intercommunicate between each other. This isn’t as scary of a process as it may sound at first. In the next article we’re going to present one of the most common problems that is often used to exemplify this process: the producer-consumer example. You won’t want to miss it! 

In closing, I’d like to invite you to join our experienced community of technology professionals who focus on all areas of IT&C, from software and hardware to consumer electronics, at Dev Hardware Forums. As well, be sure to check out the community of our sister site at Dev Shed Forums. We are friendly and we’ll do our best to help you.

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort