You are on page 1of 1

Sign in Get started

T OP S T ORY S UBMIT

You have 2 free stories left this month. Sign up and get an extra one for free.

Java Multithreading
Kasun Dissanayake Follow
May 28, 2019 · 8 min read

The ability to execute several programs simultaneously is called


Multitasking. In system’s terminology is called as Multithreading. Here
the main program is divided into two or more subprograms (processes)
which can be implemented at the same time parallel.

Examples:

Railway ticket reservation system where multiple customers accessing


the server.

Performing some execution while I/O block.

Games are very good examples of threading. You can use multiple
objects in games like cars, motorbikes, animals, people, etc. All these
objects are nothing but just threads that run your game application.

Multiple account holders accessing their accounts simultaneously on


the server. When you insert an ATM card, it starts a thread for
performing your operations.

Typing MS Word document while listening to music.

What is Thread?
A thread is similar to a program that has a single flow of control. Every
program has at least one thread and the thread has a beginning, body
and an end. And it executes commands sequentially. So Multithreading
means executing more than one commands in parallel. The special thing
is Java supports for the Multithreading.

So Java enables us to use multiple flows of control in developing


programs. Each flow of control (Thread) runs in parallel to others. A
program which contains multiple flows of control called a
MultiThreaded Program.

Let's assume that the program has Threads like

Main Thread
Thread A
Thread B
Thread C

Now first of all the main Thread initiate. Then Thread A, B, and C run
concurrently and share the resource jointly. Since threads in Java are
subprograms of the main application program and share the same
memory space, they are known as Light- Weight Threads.

Important: Remember threads running in parallel does not really


mean that they run at the same time. All the threads are running
on a single processor and the execution shared between the
threads. The Java compiler handles switching the control between
the threads.

The life cycle of a Thread


During the lifetime of a Thread, There are many states it can enters.

Newborn State — When we create a thread Object, The Thread is


born and it is in the newborn state.

Runnable State — Thread is ready for execution and waiting for the
availability of processor.

Running State — The processor has given it’s time to the execution.

Blocked State — Thread is prevented from entering into the


runnable state and running state. This happens when the Thread is
suspended, slept or waited in order to satisfy certain requirements.

Dead State — Running Thread ended his life cycle and completed
executing the run method.

Thread Exceptions
Sleep() method should enclose in a try block and follow by a catch block.
This is important because the sleep method throws an exception which
should be caught. If we do not catch the exception the program will not
compile.

Java will throw an exception named IllegalThreadStateException


whenever we attempt to invoke a method that a thread cannot handle in
a given state.

Example: Sleeping method cannot deal with the resume() method


because the sleeping thread cannot receive any instructions.

How to create a Thread?


There are two ways to create a thread:

1. By extending Thread class

2. By implementing Runnable interface.

The approach can be used depending on what the class we are creating
require.

1. By extending Thread class


Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and
implements Runnable interface.

Steps:
Declare the class as extending the Thread Class.

Implement the run method.

Create the thread Object and call the Start method.

package threadtutorial;

/**
*
* @author Kasun Dissanayake
*/

class Multi extends Thread{


@Override
public void run(){
//your code here
System.out.println("thread is running...");
}
}
public class ThreadTutorial {

public static void main(String[] args) {


Multi t1 = new Multi();
t1.start();

Here Multi t1 = new Multi(); statement creates the Object. The Thread
that will run this Object is not yet running. The Thread is in a newborn
state.

Now t1.start(); statement leads the thread move to the runnable state.
Then the Java interpreter will schedule the thread to run by invoking this
run() method. Now the Thread is in running state.

Run this code segment then you will get a result like this.

How to stop a Thread?


Whenever we want to stop a Thread from running state we should call
it’s stop() method. It will move the Thread’s Running state to the Dead
state.

The thread will move to the dead state automatically when it reaches the
end of its method.

Example :

A program which includes a thread to display numbers 1 to 10. If the


number reaches to 5, stop the thread.

package threadtutorial;

/**
*
* @author Kasun Dissanayake
*/

class Test extends Thread{


public void run(){
for (int i = 0; i < 10; i++) {
if(i == 5){
stop();
}
System.out.println(i);
}
}
}

public class ThreadTutorial {

public static void main(String[] args) {

Test test = new Test();


test.start();

}
}

How to Block a Thread?


A Thread can temporarily be suspended or blocked from entering to the
Runnable and subsequently running state by using,

sleep(); —Thread gets started after a specified time interval unless it


is interrupted.

suspend(); — This method puts a thread in the suspended state and


can be resumed using resume() method.

wait(); — Causes the current thread to wait until another thread


invokes the notify().

notify(); — Wakes up a single thread that is waiting on this object’s


monitor.

resume(); — This method resumes a thread, which was suspended


using suspend() method.

stop(); — This method stops a thread completely.

The difference between wait() and sleep()


wait() is an instance method that’s used for thread
synchronization. It can be called on any object, as it’s defined right on
java.lang. Object, but it can only be called from a synchronized block.
It releases the lock on the object so that another thread can jump in and
acquire a lock. On the other hand, Thread.sleep() is a static method that
can be called from any context. Thread.sleep() pauses the current
thread and does not release any locks.

When we use the sleep() method, a thread gets started after a specified
time interval, unless it is interrupted.

For wait(), the waking up process is a bit more complicated. We can wake
the thread by calling either the notify() or notifyAll() methods on the
monitor that is being waited on.

Use notifyAll() instead of notify() when you want to wake all threads that
are in the waiting state. Similarly to the wait()method itself, notify(), and
notifyAll() have to be called from the synchronized context.

Example :

Write a program using threads to display numbers 1 to 10. If the number


equals to 5 sleep the thread 5000 milliseconds. (Here Sleep() method
should enclose in a try block and follow by a catch block.)

package threadtutorial;

/**
*
* @author Kasun Dissanayake
*/

class Test extends Thread{


public void run(){
for (int i = 0; i < 10; i++) {
if(i == 5){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(i);
}
}
}

public class ThreadTutorial {

public static void main(String[] args) {

Test test = new Test();


test.start();

}
}

Thread Priority
In Java, we can assign a priority to a Thread which affects the order in
the schedule for running. The Threads which have the same priority has
an equal priority (This done by the Java scheduler) and they share the
processor on a first come first serve manner.

We can set a Priority of a Thread using setpriority() method as follows.

Threadname.setpriority(int number);

the number is an Integer value (value between 1 -10)which is the


Thread’s priority.

Thread class defines several priority constants.

MIN_PRIORITY = 1

MAX_PRIORITY = 10

Default setting is NORM_PRIORITY. This is equal to value 5.

Exercise:
A program which includes Class A and Class B. The Class A uses a thread
to display numbers from 1–10 and Class B uses a Thread to display
numbers 10 -1. Priority as Class A Thread — Max and Class B Thread
— Min

package threadtutorial;

/**
*
* @author Kasun Dissanayake
*/

class A extends Thread{


public void run(){
System.out.println("Class A method...");
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}

class B extends Thread{


public void run(){
System.out.println("Class B method...");
for (int i = 10; i > 0; i--) {
System.out.println(i);
}
}
}
public class ThreadTutorial {

public static void main(String[] args) {


A a = new A();
B b = new B();

a.setPriority(Thread.MAX_PRIORITY);
b.setPriority(Thread.MIN_PRIORITY);

a.start();
b.start();

Execute the code. Then you will get a result like this.

Synchronization
In the run, method Threads try to use some resources which lie inside
the run method as well as outside the run method. If two Threads try to
reach the same resource there may be happening a problem. Then Java
gives us a technique to overcome this problem named
Synchronization. Here we can use a synchronized method to
implement Synchronization mechanism.

The synchronization is mainly used to

1. To prevent thread interference.

2. To prevent consistency problem.

When we declare a method as synchronized, Java creates a monitor and


hand it over to the Thread which is first called. Other threads cannot
access to that synchronized code segment.

Example:

//example of java synchronized method


class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

class MyThread2 extends Thread{


Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class Example6{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Execute the code and you will get a result like this.

Here, MyThread1 invokes a synchronized method, it automatically


acquires the lock for that object and releases it when the thread
completes its task.

Then the second thread MyThread2 invokes and executes.

2. By implementing Runnable interface


The runnable interface declares the run() method that is required for
implementing threads in our programs.

Steps:
Declare the class as implementing the Runnable Interface.

Implement the run method

Create a thread by defining an Object that is instantiated from this


runnable class as the target of the Thread

Call the thread’s start() method to run the thread

package threadtutorial;

/**
*
* @author Kasun Dissanayake
*/

class Test implements Runnable{


public void run(){
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}

public class ThreadTutorial {

public static void main(String[] args) {

Test test = new Test();


Thread thread = new Thread(test);
thread.start();

}
}

As always, you can check out the examples provided in this article over
on GitHub.

Thank you!

Java T hreading In Java Multithreading

981 claps

WRIT T EN BY

Kasun Dissanayake Follow

Software Engineer at Pearson Lanka || Former Associate


Software Engineer at hSenid Software International

The Startup Follow

Medium's largest active publication, followed by +656K


people. Follow to join our community.

See responses (2)

More From Medium

Reference copy , Shallow Encapsulation in Python Django and Stripe 3 Ways to Execute
copy and Deep Copy Coder’s Cat in Better Integration Commands in a Docker
Nitish Prasad in T he Startup Programming Ordinary Coders in T he Container
Startup Nasi Jofche in Better
Programming

A Deep Dive into the How to build a GraphQL Multiple Tool Versions Picking the Right
Flutter Animations server with Swift and via Homebrew Arduino
package Vapor Andreas Siegel James Lewis in Hackster Blog
Martin Rybak in Flutter NYC Alexander Steiner

Discover Medium Make Medium yours Become a member


Welcome to a place where words matter. On Medium, smart Follow all the topics you care about, and we’ll deliver the Get unlimited access to the best stories on Medium — and
voices and original ideas take center stage - with no ads in best stories for you to your homepage and inbox. Explore support writers while you’re at it. Just $5/month. Upgrade
sight. Watch

About Help Legal

You might also like