Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Java Multithreading

Sabyasachi Moitra
moitrasabyasachi@hotmail.com
What is Thread?
O A lightweight sub-process.
O A smallest unit of processing.
O It shares a common memory area.
O Threads are independent, i.e., if there
occurs exception in one thread, it doesn't
affect other threads.
O A process can have multiple threads.

2
Multitasking
O Multitasking is a process of executing
multiple tasks simultaneously.
O Multitasking is used to utilize the CPU.
O Multitasking can be achieved by two ways:
- Process-based (Multiprocessing)
- Thread-based (Multithreading)

3
Multiprocessing
O Each process have its own address in
memory, i.e., each process allocates
separate memory area.
O Process is heavyweight.
O Cost of communication between the process
is high.
O Switching from one process to another
require some time for saving and loading
registers, memory maps, updating lists etc.
4
Multithreading
O Multithreading is a process of executing multiple
threads simultaneously.
O Threads share the same address space.
O Thread is lightweight.
O Cost of communication between the thread is
low.
O Context-switching between the threads takes
less time than process.
O It doesn't block the user because threads are
independent and can perform multiple
operations at same time.

5
Thread Life Cycle

6
Thread Life Cycle (2)
O New
- The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
O Runnable
- The thread is in runnable state after invocation of start() method, but
the thread scheduler has not selected it to be the running thread.
O Running
- The thread is in running state if the thread scheduler has selected it.
O Non-Runnable (Blocked)
- This is the state when the thread is still alive, but is currently not
eligible to run.
O Terminated
- A thread is in terminated or dead state when its run() method exits.

7
The Main Thread
O When a Java program starts up, one thread
begins running immediately, called the main
thread of the program.
O It is the one that is executed when a
program begins.
O It is the thread from which other “child”
threads will be produced.
O It is the last thread to finish execution
because it performs various shutdown
actions.
8
Thread Scheduler
O Thread scheduler in java is the part of the
JVM that decides which thread should run.
O There is no guarantee that which runnable
thread will be chosen to run by the thread
scheduler.
O Only one thread at a time can run in a single
process.
O The thread scheduler mainly uses pre-
emptive or time slicing scheduling to
schedule the threads.
9
Sleeping a Thread
O The sleep() method of Thread class is used
to sleep a thread for the specified amount of
time.
O If you sleep a thread for the specified time,
the thread scheduler picks up another
thread and so on, as only one thread is
executed at a time.

10
Creating Thread
There are two ways to create a thread:
O By implementing Runnable interface.
O By extending Thread class.

11
By implementing Runnable interface

12
By extending Thread class

13
// Create multiple threads
class ChildThread implements Runnable
{
String tname; // name of thread
Thread t;

ChildThread(String tname)
{
this.tname=tname;
t=new Thread(this);
t.start(); // Start the thread
}

// This is the entry point for the second thread


public void run()
{
System.out.println("Starting "+this.tname+" thread.");

try
{
for(int i=1;i<=5;i++)
{
System.out.println(this.tname+": "+i);
Thread.sleep(500);
}
}
catch(Exception e)
{
System.out.println(e.toString());
}

System.out.println("Exiting "+this.tname+" thread.");


14
}
}
public class MainThread
{
public static void main(String args[])
{
ChildThread ct1 = new ChildThread("one"); // start threads
ChildThread ct2 = new ChildThread("two");

System.out.println("Starting main thread.");

try
{
for(int i=1;i<=5;i++)
{
System.out.println("Main Thread: "+i);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e.toString());
}

System.out.println("Exiting main thread.");


}
}

15
Output
Starting main thread.
Main Thread: 1
Starting one thread.
one: 1
Starting two thread.
two: 1
two: 2
one: 2
one: 3
two: 3
Main Thread: 2
two: 4
one: 4
Main Thread: 3
two: 5
one: 5
Exiting one thread.
Exiting two thread.
Main Thread: 4
Main Thread: 5
Exiting main thread.

16
isAlive( ) & join( ) Methods
isAlive( )
The isAlive( ) method checks if the thread
upon which it is called is still running or not.
join( )
The join() method waits for a thread to die.

17
// Using join() to wait for threads to finish
class ChildThread implements Runnable
{
String tname; // name of thread
Thread t;

ChildThread(String tname)
{
this.tname=tname;
t=new Thread(this);
t.start(); // Start the thread
}

// This is the entry point for the second thread


public void run()
{
System.out.println("Starting "+this.tname+" thread.");

try
{
for(int i=1;i<=5;i++)
{
System.out.println(this.tname+": "+i);
Thread.sleep(500);
}
}
catch(Exception e)
{
System.out.println(e.toString());
}

System.out.println("Exiting "+this.tname+" thread.");


18
}
}
public class MainThread
{
public static void main(String args[])
{
ChildThread ct1 = new ChildThread("one"); // start threads
ChildThread ct2 = new ChildThread("two");

System.out.println("Starting main thread.");

System.out.println("Thread One is alive: "+ ct1.t.isAlive());


System.out.println("Thread Two is alive: "+ ct2.t.isAlive());

// wait for threads to finish


try
{
for(int i=1;i<=5;i++)
{
System.out.println("Main Thread: "+i);
Thread.sleep(1000);
}

System.out.println("Waiting for threads to finish.");


ct1.t.join();
ct2.t.join();
}
catch(Exception e)
{
System.out.println(e.toString());
}

System.out.println("Thread One is alive: "+ ct1.t.isAlive());


System.out.println("Thread Two is alive: "+ ct2.t.isAlive());
19
System.out.println("Exiting main thread.");
}
}
Starting main thread.
Thread One is alive: true
Thread Two is alive: true
Main Thread: 1
Starting two thread.
two: 1
Starting one thread.
one: 1
two: 2
one: 2
Main Thread: 2
two: 3
one: 3
two: 4
one: 4
Main Thread: 3
two: 5
one: 5
Exiting two thread.
Exiting one thread.
Main Thread: 4
Main Thread: 5
Waiting for threads to finish.
Thread One is alive: false
Thread Two is alive: false
Exiting main thread.
20
Thread Priority
O Each thread have a priority that helps the
operating system determine the order in which
threads are scheduled.
O Priorities are represented by a number between
1 and 10.
O Java thread priority constants:
- MIN_PRIORITY (a constant of 1)
- NORM_PRIORITY (default priority, a constant of
5)
- MAX_PRIORITY (a constant of 10)

21
class ChildThread implements Runnable
{
Thread t;

ChildThread(String tname,int tp)


{
t=new Thread(this);
t.setName(tname); //setting thread name
t.setPriority(tp); //setting thread priority
t.start(); // Start the thread
}

// This is the entry point for the second thread


public void run()
{
System.out.println("Starting thread: "+t.getName()); //getting thread name
System.out.println("Starting thread priority: "+t.getPriority()); //getting thread priority

try
{
for(int i=1;i<=5;i++)
{
System.out.println(t.getName()+": "+i);
Thread.sleep(500);
}
}
catch(Exception e)
{
System.out.println(e.toString());
}

System.out.println("Exiting thread: "+t.getName());


22
}
}
public class MainThread
{
public static void main(String args[])
{
ChildThread ct1 = new ChildThread("one",7); // start threads
ChildThread ct2 = new ChildThread("two",2);
ChildThread ct3 = new ChildThread("three",5);

System.out.println("Starting main thread.");

try
{
for(int i=1;i<=5;i++)
{
System.out.println("Main Thread: "+i);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e.toString());
}

System.out.println("Exiting main thread.");


}
}
23
Starting thread: one
Starting thread priority: 7
one: 1
Starting main thread.
Main Thread: 1
Starting thread: three
Starting thread priority: 5
three: 1
Starting thread: two
Starting thread priority: 2
two: 1
one: 2
three: 2
two: 2
one: 3
Main Thread: 2
three: 3
two: 3
one: 4
three: 4
two: 4
Main Thread: 3
one: 5
three: 5
two: 5
Exiting thread: one
Exiting thread: three
Exiting thread: two
Main Thread: 4
Main Thread: 5 24
Exiting main thread.
References
O Courtesy of JavaTPoint – Java Tutorial. URL:
https://www.javatpoint.com/java-tutorial
O Herbert Schildt, Java: The Complete
Reference, Seventh Edition, TMGH, 2007
O Courtesy of TutorialsPoint – Java Tutorial.
URL: https://www.tutorialspoint.com/java

25

You might also like