Threading , Multithreading made easy (using java)

Yuvraj Agarkar
9 min readMay 15, 2021

Hey everyone , hope ya’ll are doing well , in this particular article we are gonna discuss what in world is Threading and how we can implement it in our upcoming projects . Everything here is mentioned in easiest form that it could ever be .So get your coffee Mug ready get excited and here we go ….!

What is threading or Multithreading ?
before understanding that let’s consider what is tasking or multitasking ,Threading and Multithreading is some somewhat similar , Let’s talk in the form of analogy here .. Many times you might have found yourself in a certain situation like talking on phone as well as cooking, Here you are performing 2 Tasks at the same time While you have only one Brain but Still the Brain Handles both , Same way You have only One Processor in your PC but still it can handle Multiple Tasks at the same time .
A thread
carries out a particular(only one) task at a time But if you want to perform 2 or more tasks simultaneously you will have to create threads accordingly.

Prerequisites : Basic knowledge of programming and Computer Systems etc .
How can you make most out of this article ?
->
Don’t by-heart a single thing try to understand more and more and revisit as many times as you want .
Everything here will be explained in java but the concept remains same universally .

How is MultiThreading Performed ?
Since You have only One processor the task of each thread are executed one by one , The java interpreter Switches so fast between the threads feels like they are handled by separate dedicated Processors but they are not .
Multithreading Gives You the Power of handling different tasks at the same time .

Implementing and Creating Threads
We can easily create thread using the Thread class that comes from java.lang.Thread , All you have to do is extend(subclass) the Thread class and override the method run() all the code that you want to run in separate thread should go in this ( run() ) method . You can consider it as a body of thread .

// CODE 1.1import java.lang.* class A extends Thread {
public void run() {
for(int i = 1;i<=5 ;i++){
System.out.println("\t From thread A i = "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread {
public void run() {
for(int j = 1;j<=5 ;j++){
System.out.println("\t From thread B i = "+j);
}
System.out.println("Exit from B");
}
}
class C extends Thread {
public void run() {
for(int z = 1;z<=5 ;z++){
System.out.println("\t From thread C i = "+z);
}
System.out.println("Exit from C");
}
}
class HelloWorld {
public static void main(String[] args) {
new A().start() ;
new B().start() ;
new C().start() ;
}
}

Let’s Trace out the above Code1.1 line by line , First We have created 3 classes and subclassed them with Thread class, overriden the run method , This means that we have created 3 different threads which will run simultaneously to complete the task, here to execute the loop . Note in Main method we have done object.start() becuase the start method is the one that’ll evoke the run() method . Note the output after you run the code Each time you run the code it will generate the same output but with different sequence and you can’t predict the exact sequence that the thread will run , You can also call it as Asynchronous Programming .

//OUTPUT1.1 From thread B i = 1From thread A i = 1
From thread A i = 2From thread A i = 3
From thread A i = 4
From thread A i = 5
Exit from A
From thread B i = 2From thread B i = 3From thread B i = 4From thread C i = 1From thread C i = 2From thread C i = 3From thread B i = 5
Exit from B
From thread C i = 4
From thread C i = 5
Exit from C

What will happen if you do object.run() instead of object.start() ?
This will execute the code Synchronously on main Single thread Which means No threading will be applied You will get the output in sequence as you run the program

Stopping or blocking a thread !!
You can also stop or block a thread from running , there can be several reasons for doing this maybe you don't want to run a thread if a particular condition occurs whatever is the reason You can stop it or block(tell it to wait) for a while
thread.stop() stops the execution of the thread and kills it , Thread Goes into a killed state whenever it is done executing or You have explicitly killed it using .stop() method , Note once killed cannot be revived
thread.sleep(time-in-milliseconds) a This will block a thread from running for a particular time , this method can throw an exception you may need to use it inside try block , Note that there is a difference between killing a thread and blocking it , once killed cannot be revived but when blocked can be used. later
thread.suspend() a blocked until further orders , this will keep the thread in block state and you can bring it back to runnable state using thread.resume()
thread.wait() block a thread until a specific condition is met , again to change it into runnable state use thread.notify().

Lifecycle of a Thread
Just Like a human or any other living being has a particular LifeCycle Threads have too … they also pass through different stages of their Life

Extra Attention on this part please … cause if you don’t understand the Lifecycle you never understand the true meaning of Life .

Whenever You create A thread object, it is in a Newborn state a baby state , Now You have several options Open here as You can see in the diagram mentioned above , First thing You can either stop(kill) it or start it(send it to runnable state)
Next state is Runnable State where all your different threads stand in a queue to execute their task and only one thread at a time is allowed to enter the running state because we have only one processor , So the processor executes each thread for a specific period of time (based on their priority (which will be discussed later on) ) and sends it back to runnable state or the queue
For-example Thread1 comes in executes itself for a bit and than go at the end of the line again thread2 comes in executes itself a bit and go back in line and so on and so forth
But these priorities can Change , Just like if there is a VVIP person standing in Line or a queue who receives a special treatment in your shop and doesn’t need to stand in queue
The most bottom part is blocked State as you can block a thread whenever You want or kill it or Revive it to runnable state as you feel .

Priorities
Threads can have priorities , You have to set them explicitly(manually) , There are priorities represented in form of Integer Numbers from 1–10 , If you don’t set any it will be defaulted to 5 which is Known as Normalised or Normal , The lowest is 1 and the highest is 10 , Let’s look at example .

// Code1.2  class A extends Thread {
public void run() {
for(int i = 1;i<=5 ;i++){
System.out.println("\t From thread A i = "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread {
public void run() {
for(int j = 1;j<=5 ;j++){
System.out.println("\t From thread B i = "+j);
}
System.out.println("Exit from B");
}
}
class C extends Thread {
public void run() {
for(int z = 1;z<=5 ;z++){
System.out.println("\t From thread C i = "+z);
}
System.out.println("Exit from C");
}
}
class HelloWorld {
public static void main(String[] args) {
A a = new A() ;
B b = new B() ;
C c = new C();
c.setPriority(Thread.MAX_PRIORITY) ;
b.setPriority(5) ;
a.setPriority(Thread.MIN_PRIORITY) ;
a.start() ;
b.start() ;
c.start() ;
}
}

thread.setPriority() allows us to set the priority of a thread , You can also get priority of any thread using getPriority() method

//OUTPUT 1.2 From thread B i = 1
From thread C i = 1
From thread C i = 2
From thread C i = 3
From thread C i = 4
From thread C i = 5
Exit from C
From thread A i = 1
From thread A i = 2
From thread A i = 3
From thread A i = 4
From thread A i = 5
Exit from A
From thread B i = 2
From thread B i = 3
From thread B i = 4
From thread B i = 5Exit from B

The Yield method
The yield method is a method from class Thread it allows us to hand over or skip the turn of the current thread , in short it can take a running thread into a runnable state .
For example You can see the below snippet ..

// Code 1.3 class A extends Thread {
public void run() {
for(int i = 1;i<=5 ;i++){
if(i==1){yield();}
else{
System.out.println("\t From thread A i = "+i);
}
}
System.out.println("Exit from A");
}
}

Synchronization
This topic is quite simple to understand imagine You live with Your Cousins or in a joint family and You share a couple of things between them so there should be proper Synchronisation a proper communication between you guys in order to make use of those things . Same Way in threading if a multiple threads are working on a shared resource or a object they(threads) need to have proper communication between each other
Java makes it easy in this case , lets create a situation here There is class Pyramid which draws a Pyramid and than there are 2 Threads A and B which share the same object of class Pyramid , So in this case the interpreter hands over a “ monitor “ to the the first thread that tries to access any method From the pyramid class to keep an eye on changes , mark each method in pyramid class with keyword synchronized after first thread finishes it’s work the “ monitor “ is handed over to next thread and so on ….
Consider the below example

// CODE 1.4 class Pyramid {
synchronized void draw(char ch) {
for(int i = 0;i<10;i+=2) {
for(int k = 10-i ;k>0 ;k -=2 ){
System.out.print(" ");
}
for(int j = 0 ; j<=i ; j++) {
System.out.print(ch) ;
}
System.out.println();
}
}
}
class A extends Thread {
Pyramid p ;
A(Pyramid p) {
this.p = p ;
}
public void run() {
p.draw('*');
}
}
class B extends Thread {
Pyramid p ;
B(Pyramid p) {
this.p = p ;
}
public void run() {
p.draw('#');
}
}
public class HelloWorld{public static void main(String []args){
Pyramid p = new Pyramid();
A a = new A(p) ;
B b = new B(p) ;

a.start() ;
b.start() ;
}
}
// OUTPUT 1.4
*
***
*****
*******
*********
#
###
#####
#######
#########

Try above code without the synchronized keyword and see the output , the reason behind taking this star pattern example was, it is very common and simple situation that’s used to explain this concept and that’s what our motto was to understand things in the simplest way possible

So That was Threading and Multithreading in a Nutshell , read this again to get a better understanding of this concept , Follow and Like the article because it takes a hell lotta time to create such content , Stay tuned to get more of such , Don’t Forget to Follow me on social media , Twitter , Medium ,Github , Instagram ,Website . I often write articles on iOS , Web Development ,Cyber Security , Coding and tech in general .

--

--

Yuvraj Agarkar

Aspiring iOS developer , Like to make other developer’s life easy, giving my best to contribute in communities like these