Threads
By
SANJIT KUMAR BARIK
Threads
class ABC Single Thread
{
public static void main(String args[ ]) Execution Starts
{
Statement – 1;
Statement – 2;
Statement – 3; Continuing Flow of
Statement – 4; Execution
Statement – n;
} Execution Ends
}
2
Threads
A Java program is executed in a particular sequence. The
program begins, runs through a sequence of executions,
and finally ends.
At a given point of time, only one statement is under
execution
So, a Single flow of control is required to execute a
Java program
Thread refers to a flow of control for a Program
3
Threads
class ABC
{
Multi-Threaded public static void main(String args[ ]) Main Thread Starts
{
}
}
Thread A Starts Thread B Starts Thread C Starts
class A class B class C
{ { {
----------
---------- CPU ---------- CPU
---------- ---------- ----------
Switching Switching
} } }
4
Threads
A Java program can be divided into sub-programs.
Each sub program must have a separate sequence
of execution i.e., a Separate flow control is required
Each sub-program must be independently executed
All sub-programs can be parallely executed
So Multiple flow of controls are found i.e., Multiple
threads are required
5
Threads
Java program contains either a single flow of control or
multiple flow of control for execution
If a Java program contains single flow of control,
then it is known as Single Threaded Program
If a Java program contains multiple flows of control
then it is known as Multithreaded Program
6
Creating Threads – run( ) method
Threads are created in the form of Objects
Thread contains a method called run( )
public void run( )
{
Statements for implementing Thread
}
7
Creating Threads - run( ) method
The run( ) method is the heart and soul of any thread
The run( ) method makes the entire body of Thread
The run( ) method is the only method that implements
Thread’s behavior
The run( ) method is invoked by an Object of Thread
8
Creating Threads - start( ) method
Thread is created. It is initiated using start( ) method
The start( ) is also a method of Thread
Thread can be created using Two methods
Extending Thread Class and overriding the run( )
Implementing Runnable Interface which has run( )
9
Extending Thread Class - overriding the run( )
class Mythread extends Thread
{ Thread Object Newborn state
public void run ( )
{
--------
Mythread aThread = new MyThread( );
}
aThread.start( );
}
JRE
Running state Runnable state
10
Extending Thread Class - overriding the run( )
Declare a Class which extends java.lang.Thread class
Implement the run( )
Create Thread object and call start( ) to initiate Thread
11
Extending Thread Class – Example 1
class A extends Thread class B extends Thread
{ {
public void run ( ) public void run ( )
{ {
for ( int i = 1; i <= 5; i++ ) for ( int j = 1; j <= 5; j++ )
{ {
System.out.println("From Thread A : i = " + i); System.out.println("From Thread B : j = " + j);
} }
System.out.println("Exit From Thread A"); System.out.println("Exit From Thread B");
} }
} }
12
Extending Thread Class – Example 1
class C extends Thread class ThreadTest
{ {
public void run ( ) public static void main(String args[ ])
{ {
for ( int k = 1; k <= 5; k++ ) new A( ).start( );
{ new B( ).start( );
System.out.println("From Thread C : k = " + k); new C( ).start( );
} }
System.out.println("Exit From Thread C"); }
}
}
D:\jdk1.8.0_111\jdk1.8.0_111\bin>javac ThreadTest.java
13
Extending Thread Class – Example 1
D:\jdk1.8.0_111\jdk1.8.0_111\bin>java ThreadTest D:\jdk1.8.0_111\jdk1.8.0_111\bin>java ThreadTest
From Thread A : i = 1 From Thread A : i = 1
From Thread A : i = 2 From Thread A : i = 2
From Thread A : i = 3 From Thread B : j= 1
From Thread A : i = 4 From Thread A : i = 3
From Thread A : i = 5 From Thread A : i = 4
Exit From Thread A From Thread A : i = 5
From Thread B : j = 1 Exit From Thread A
From Thread B : j = 2 From Thread B : j = 2
From Thread B : j = 3 Run 1 From Thread B : j = 3 Run 2
From Thread B : j = 4 From Thread B : j = 4
From Thread B : j = 5 From Thread B : j = 5
Exit From Thread B Exit From Thread B
From Thread C : k = 1 From Thread B : k = 1
From Thread C : k = 2 From Thread B : k = 2
From Thread C : k = 3 From Thread B : k = 3
From Thread C : k = 4 From Thread B : k = 4
From Thread C : k = 5 From Thread B : k = 5
Exit 14
From Thread C Exit From Thread C
Extending Thread Class – Example 1
D:\jdk1.8.0_111\jdk1.8.0_111\bin>java ThreadTest D:\jdk1.8.0_111\jdk1.8.0_111\bin>java ThreadTest
From Thread A : i = 1 From Thread A : i = 1
From Thread A : i = 2 From Thread A : i = 2
From Thread A : i = 3 From Thread A : i = 3
From Thread A : i = 4 From Thread B : j = 1
From Thread A : i = 5 From Thread B : j = 2
Exit From Thread A From Thread B : j = 3
From Thread B : j = 1 From Thread B : j = 4
From Thread B : j = 2 From Thread B : j = 5
From Thread B : j = 3 Run 3 Exit From Thread B
From Thread B : j = 4 From Thread A : i = 4 Run 4
From Thread B : j = 5 From Thread A : i = 5
Exit From Thread B Exit From Thread A
From Thread C : k = 1 From Thread C: k = 1
From Thread C : k = 2 From Thread C: k = 2
From Thread C : k = 3 From Thread C : k = 3
From Thread C : k = 4 From Thread C: k = 4
From Thread C : k = 5 From Thread C : k = 5
Exit From Thread C Exit From Thread C
15
Threads – stop( ), sleep( ), suspend( ), wait( )
aThread.stop( ); Moving a Thread to Dead state
aThread.sleep( ); Block a Thread to Specified Time
aThread.suspend( ); Block a Thread until further Orders
aThread.wait( ); Block a Thread until a Condition occurs
16
Life Cycle of a Thread
New Thread New Born
stop
start
stop
Active Thread Running Runnable Dead
yield
Killed Thread
suspend resume
sleep notify stop
wait
Blocked Idle Thread
17
Life Cycle of a Thread – New Born State
New Born State: Thread is created
Thread is invoked using
Thread.start( );
Moving a Thread to Runnable state
Thread Object is killed using
Thread.stop( );
Moving a Thread to Dead state
18
Life Cycle of a Thread – Runnable State
Runnable State:
Thread is ready for execution
Thread is waiting in Queue to get CPU
19
Life Cycle of a Thread – Runnable State
Runnable State:
Round Robin: Equal Time Slots for Threads with
same Priorities
Thread.yield( ): Relinquish Control from Running
Thread and move it to Runnable State
Threads may be assigned Priorities
Threads are arranged based on Priorities
20
Life Cycle of a Thread – Running State
Running State: Thread is executed in CPU
21
Life Cycle of a Thread – Running State
Thread.stop( ); Moving a Thread to Dead state
Thread.suspend( ); Block a Thread until further Orders
Resumed
Thread.sleep( ); Block a Thread to Specified Time (ms)
Thread.wait( ); Block a Thread until a Condition occurs
Notified
22
Life Cycle of a Thread – Blocked State
Blocked State: To satisfy the requirements
Thread is suspended
Thread is sleeping
Thread is waiting
23
Life Cycle of a Thread – Dead State
Dead State:
Life of the Thread Ends
Thread Completes its execution
Thread is killed after
New born
Running/ Runnable
Blocked
24
Thread Methods – Example 2
class A extends Thread class B extends Thread
{ {
public void run ( ) public void run ( )
{ {
for ( int i = 1; i <= 5; i++ ) for ( int j = 1; j <= 5; j++ )
{ {
if ( i == 1) yield( ); System.out.println("From Thread B : j = " + j);
System.out.println("From Thread A : i = " + i); if ( j == 3 ) stop( );
} }
System.out.println("Exit From Thread A"); System.out.println("Exit From Thread B");
} }
} }
25
Thread Methods – Example 2
class C extends Thread class ThreadTest2
{ {
public void run ( ) public static void main(String args[ ])
{ {
for ( int k = 1; k <= 5; k++ ) A threadA = new A( );
{ B threadB = new B( ); C
System.out.println("From Thread C : k = " + k); threadC = new C( );
if ( k == 1 ) System.out.println(" Start
try Thread A ");
{ threadA.start( );
sleep(1000); System.out.println(" Start Thread B ");
} threadB.start( );
catch( Exception e) { } System.out.println(" Start Thread C ");
threadC.start( );
} System.out.println(" End of Main Thread
System.out.println("Exit From Thread C"); ");
} }
} }
26
Thread Methods – Example 2
27
Thread Priorities
setPriority(intNumber) – Sets priority for a Thread
intNumber may take values from 1 to 10
Thread class contains several priority constants
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
NORM_PRIORITY is default – Many user level
processes uses it with +/- 1)
28
Thread Priorities – Example 3
import java.io.*; class B extends Thread
class A extends Thread {
{ public void run()
public void run() {
{ for(int j=1;j<=5;j++)
for(int i=1;i<=5;i++) {
{ System.out.println(j + "*" +5+ "=" +(j*5));
System.out.println(i + "*" +3+ "=" +(i*3)); }
} System.out.println("End of the 2nd Thread");
System.out.println("End of the 1st Thread"); }
} }
}
29
Thread Priorities – Example 3
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println(k + "*" +7+ "=" +(k*7));
}
System.out.println("End of the 3rd Thread");
}
}
30
Thread Priorities – Example 3
public class Multithread
{
public static void main(String args[ ])throws IOException
{
A ThreadA=new A();
B ThreadB=new B();
C ThreadC=new C();
ThreadA.setPriority(Thread.NORM_PRIORITY);
ThreadB.setPriority(Thread.MAX_PRIORITY);
ThreadC.setPriority(Thread.MIN_PRIORITY);
System.out.println("The priority of Thread A is "+ThreadA.getPriority());
System.out.println("The priority of Thread B is "+ThreadB.getPriority());
System.out.println("The priority of Thread C is "+ThreadC.getPriority());
ThreadA.start();
ThreadB.start();
ThreadC.start();
}
}
31
Thread Priorities – Example 3
D:\jdk1.8.0_111\jdk1.8.0_111\bin>java Multithread
The priority of Thread A is 5
The priority of Thread B is 10
The priority of Thread C is 1
1*5=5
2*5=10
3*5=15
4*5=20
5*5=25
End of the 2nd Thread
1*3=3
2*3=6
3*3=9
4*3=12
5*3=15
End of the 1st Thread
1*7=7
2*7=14
3*7=21
4*7=28
5*7=35
End of the 3rd Thread
32
Implementing Runnable Interface
Runnable interface declares run( ) method
Declare a class that implements Runnable interface
Implement run( )
Create a Thread by defining an object that is instantiated
from this “runnable” class of as the target of the Thread
Call the Thread’s start( )
33
Implementing Runnable Interface – Example 4
class X implements Runnable
{
public void run( )
{
for(int i = 1; i <= 10; i++)
{
System.out.println(“\t ThreadX :
“ + i );
}
System.out.println(“End of ThreadX “ );
}
}
34
Implementing Runnable Interface – Example 4
Class RunnableTest
{
public static void main(String args[ ])
{
X runnable = new X( );
Thread threadX = new Thread(runnable);
threadX.start( );
System.out.println(“End of main Thread“ );
}
}
35
Implementing Runnable Interface – Example 4
36
References
Programming with Java – A Primer - E. Balagurusamy, 3rd
Edition, TMH
37
Thank You
38