Multithreading in Java

Lakshan Madhuranga
5 min readDec 26, 2020

--

Hello solvers…..

In this blog I have explained about what is multithreading concept, how works multithreading in Java and how to implement simple program using threads.

If you have an idea to expert with Java, this concept is very important because multithreading concept is very useful when we develop large software.

So let’s get start…..

What is multithreading concept

Before understand this concept we should consider about multitasking. So what is multitasking, let’s get a real world example most of the developers are listing music when they coding, so there are two task happen same time as parallelly. This concept is multitasking.

When we consider about one task there may be more number of sub task (process). So When we coding in an any IDE, at the same time syntax are also check by IDE. Inside main process, there are sub processes like typing, syntax check, so this sub processes are called thread.

In here, I have mention 4 sub tasks that processes by IDE when we code. So these are the threads.

Simply thread is unit of a process, and other word if we break a main process in to number of pieces these pieces call thread.

Why we need multithreading

Every java application has at least one thread as an example main java class also a thread. So when we run an application that app is run on a CPU. CPU has cores, apps are run inside those cores. So CPUs are change with number of cores like single core, dual core, quad core, octa-core likewise. When you run a java app that app’s sub processes are run each cores because of that we can use full power of CPU.

As an example, we have an app, if we run that in one core CPU then app get 8 seconds to run. But if we want to run this app in four core CPU, we want to 4 threads, so app get only 2 seconds to run. Because 4 threads are run parallel. So you can understand how helps thread concept to reduce run time of an app.

In mobile app development there are use threads frequently. As an example let’s say we have an app that app request to a web server for to get some data so there might be some time in that time mobile app are freeze. Actually in that movement there are run 2 threads, one is for send a request and other one is for run the main UI in app. We it as asynctask.

When we develop a java web application there are use servlets. Servlets are use threading concepts. As an example when five users are request to one servlet same time then web server want to create five deferent servlets. So it’s not efficient way. When we use thread concept for this, then create five different threads for this. Because of that five users can access same time to the same servlet.

Thread life cycle

New: New threads are creating in this phase.

Runnable: A thread that ready to run.

Running: When the thread starts executing, then the state is changed to “running” state. The scheduler selects one thread from the thread pool, and it starts executing in the application.

Waiting: In an application there may be multiple threads, so there should be synchronization between threads. To do this basically one thread should be wait at one time.

Dead: In this phase, the thread is terminated after running completed.

How we use thread concept in programming

We have two ways to create threads in java.

  1. Creating Thread class

2. Using Runnable interface

Specially we can use runnable interface when we want to extend with another class, because if we use thread class we can’t use in that time. Because java has not support multiple inheritance.

In thread class and runnable interface has different methods like sleep, stop, wait, join likewise.

Implementation Sample program using thread class

First you need to create simple java project. You can use any IDE.

When we run this program without threads that’ll print five times as “Hello” and then print five times as “World”.

If we want to print as a parallelly way that’s mean once print “Hello” and then print “World” likewise. How we do that?? Let’s see…

package lk.ac.kln.Solvo;

class Hello extends Thread {
//Print five times as Hello
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Hello");
try {Thread.sleep(500);} catch (Exception e) {}
}
}

}


class World extends Thread{
//Print five times as World
public void run(){
for (int i=0; i<5; i++){
System.out.println("World");
try {Thread.sleep(500);}catch (Exception e){}
}
}
}

public class Main {

public static void main(String[] args) {

Hello o1 = new Hello();
World o2 = new World();

o1.start();
try {Thread.sleep(10);} catch (Exception e) {}
o2.start();



}
}
Output

In here you can see there are run method in both class. It should be as run because when start a thread always call to the run method. That run method is internal method of thread class.

Implementation sample program using runnable interface

In here I have implemented same program using runnable interface. This is a functional interface, there are only one method called run.

package lk.ac.kln.Solvo;

class Hello2 implements Runnable {
//Print five times as Hello
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Hello");
try {Thread.sleep(500);} catch (Exception e) {}
}
}

}


class World2 implements Runnable{
//Print five times as World
public void run(){
for (int i=0; i<5; i++){
System.out.println("World");
try {Thread.sleep(500);}catch (Exception e){}
}
}
}


public class Runn {

public static void main(String[] args) {

Runnable o1 = new Hello2();
Runnable o2 = new World2();

Thread t1 = new Thread(o1);
Thread t2 = new Thread(o2);

t1.start();
try {Thread.sleep(10);} catch (Exception e) {}
t2.start();
}
}

We can’t use start method directly when use runnable. We should create thread objects and then we can start each thread.

I hope you’ll can get small idea about thread in Java from this blog. Because I have explained only few things here, so in addition there are lots of things related to thread concept.

!!!……..

--

--

Lakshan Madhuranga
Lakshan Madhuranga

Written by Lakshan Madhuranga

Undergraduate at university of Kelaniya, and Studies ICT in faculty of computing and technology.

No responses yet