MultiThreading Fundamentals
MultiThreading Fundamentals
Threading
Content
• Multi-Threading Fundamentals
• Joining Threads
• Thread Priorities
• Synchronization
• Thread Communication
2
Multithreading Fundamentals
• Similar to Multiprocessing (OS can run several processes at the
same time)
• Only one process is actually executing at any given time. However, the
system appears to be running several programs simultaneously
4
Multithreading Fundamentals
• Multithreading allows concurrent execution of two or more
parts of a program for attaining maximum utilization of CPU
• E.g.
• We have a program whose one part is sending a file over the network, another
part is reading the input from the keyboard while some other part is buffering the
next block of data to send
Thread 1
Multiple threads
Thread 2
Thread 3
sharing a single
Process
5
Multithreading Fundamentals
• Threads Support in Java
7
Multithreading Fundamentals
• All the other threads will be created from the main thread
8
• Thread States
• A thread can only be in one of the five states:
• New
• Runnable
• Running
• Non Runnable (Waiting/Blocked/Sleeping)
• Dead or Terminated
Transitions
9
Thread States & Transitions
10
• Thread States
• New
Transitions
11
Thread States & Transitions
• Thread States
• Runnable
• This is the state when a thread is considered eligible to run, but the scheduler has
not selected it to be the running thread
• A thread first enters the runnable state when the start() method is invoked
• A thread can also return to the runnable state after either running or coming back
from a blocked, waiting, or sleeping state
12
Thread States & Transitions
• Thread States
• Running
• A thread is in the running state if the
thread scheduler has selected it
• Completed
13
Thread States &
Transitions
• Thread States
14
Thread States & Transitions
• Thread States
• Dead or Terminated
15
Creating Threads
• A thread can be created using any of the two ways
16
Creating Threads
• Thread Class
17
Creating Thread
• Thread class
• Thread class defines many methods for managing threads, few of these
methods are:
18
Creating Threads
• Thread class
• run() method is used to perform some action for the thread. It can call
other methods, declare variables or use other classes just like the main
thread
19
• Thread class
• In order to create a thread using Thread class, you’ll
need to override the run() method
• This method provides an entry point for the thread & its
syntax is
20
Creating Threads
• Thread class – Example
• What it does?
23
Creating Threads
• Example contd…
• Example contd…
25
Creating Threads
• Example contd…
Output:
public class ThreadTester {
public static void main( String args[] ) Creating Thread-1
{ Starting Thread-1
PrintThread thread1, thread2, thread3, thread4; Creating Thread-2
Starting Thread-2
Running Thread-1
thread1 = new PrintThread( "thread1" ); Thread: Thread-1, 4
thread2 = new PrintThread( "thread2" ); Running Thread-2
thread3 = new PrintThread( "thread3" ); Thread: Thread-2, 4
thread4 = new PrintThread( "thread4" ); Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
System.err.println( "\nStarting threads" ); Thread: Thread-2, 2
Thread: Thread-1, 1
thread1.start(); Thread: Thread-2, 1
thread2.start(); Thread Thread-1 exiting..
Thread Thread-2 exiting..
thread3.start();
thread4.start();
• Runnable Interface
• First step is to implement the run() method that provides an action point
for the thread and contain the complete business logic inside it
OR
Thread(Runnable threadObj)
27
Creating Threads
• Runnable Interface
• Launching a new thread:
3) Finally start the thread
1) Make a Runnable object (the thread’s job)
myThread.start();
2) Make a Thread object (the worker) and give it a Runnable (the job)
28
Creating Threads
• Runnable Interface – Example
// Let the thread sleep for a while.
class RunnableDemo implements Runnable {
Thread.sleep(50);
private Thread t; }
private String threadName; } catch (InterruptedException e) {
System.out.println("Thread " +
threadName + " interrupted.");
RunnableDemo( String name) { }
threadName = name; System.out.println("Thread " +
threadName + " exiting.");
System.out.println("Creating " +
threadName ); }
}
public void start () {
System.out.println("Starting " +
threadName );
public void run() {
if (t == null) {
System.out.println("Running " + threadName );
t = new Thread (this, threadName);
try { t.start ();
for(int i = 4; i > 0; i--) { }
System.out.println("Thread: " + }
threadName + ", " + i); }
29
Creating Threads
} Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
30
Creating Threads
• Another Example – Runnable Interface
31
Creating Threads
• Example contd…
• E.g.
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.run();
}
• In this case, the thread won’t create a new call stack, instead will start running in
the current call stack (i.e., call stack of main thread)
33
Creating Threads
• Special Cases
• A thread cannot be started twice (calling the start() method twice on the same
thread)
• When the second thread is called second time (using start()), it will throw an
IllegalThreadStateException
• E.g.
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
mt.start(); //Exception thrown
}
34
What to
Choose?
35
Joining Threads
• Sometimes, one thread needs to
know when other thread is
terminating
36
Joining Threads
• Example – isAlive()
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
37
Joining Threads
• Example – without using join()
public class MyThread extends Thread public static void main(String[] args)
{ {
MyThread t1=new MyThread();
public void run()
MyThread t2=new MyThread();
{ t1.start();
38
• In the previous example, we created two threads t1 & t2
• Similarly, thread t2 starts and prints “r1” on the console & goes to
sleep for 500 ms
• After that thread t1 wakes up from sleep and prints “r2” similarly,
thread t2 wakes up and prints “r2”
Joining
Threads
• What if, we want thread t1 to finish its execution before t2 starts
39
Joining Threads
• Example – using join()
public class MyThread extends Thread t1.start();
try{
{
}catch(InterruptedException ie){ } }
System.out.println("r2 ");
Output
}
r1
public static void main(String[] args)
r2
{
• Join method on thread t1 ensures that it
r1
finishes its execution before thread t2
r2
MyThread t1=new MyThread(); starts
MyThread t2=new MyThread();
40
Thread Priorities
• If a thread enters the Runnable state, and it has a higher priority than of the
threads in the thread-pool then the lower priority thread will be taken back to
Runnable state and the higher priority thread will be chosen to run
• In most cases, the running thread will of equal or greater priority than the
highest priority threads in the pool
41
Thread Priorities
42
Thread Priorities
43
Thread Priorities
44
Thread Priorities
45
Create Custom Thread with user-defined
name and Priority
46
Create Custom Thread with user-defined
name and Priority
47
Create Custom Thread with user-defined
name and Priority
48
Output
49
• Constants defined in Thread class
• There are 3 constants that defines the priority of a thread, these are
Thread
Priorities
50
Thread Priorities
• Demo Example – Checking the CPU usage
int count;
Thread thrd;
52
Thread Priorities
• Demo Example
class PriorityDemo { System.out.println("Low priority thread counted
public static void main(String args[]) { to " +
Priority mt1 = new Priority("High Priority"); mt2.count);
Priority mt2 = new Priority("Low Priority");
}
// set the priorities
}
mt1.thrd.setPriority(Thread.NORM_PRIORITY+2);
mt2.thrd.setPriority(Thread.NORM_PRIORITY-2); Sample run:
// start the threads High Priority starting.
mt1.thrd.start();
In High Priority
mt2.thrd.start(); Giving mt1 a
higher priority Low Priority starting.
try {
than mt2
mt1.thrd.join(); In Low Priority
53
Threads
54
Thread
55
Thread Creation
56
Thread Creation
57
Thread Creation
58
Thread Creation
59
Thread Creation
60
Difference between Sleep & Wait
61
Thread extends
62
Threads Runnable
63
Thread Multiple Threads
64
Exercise
65
Exercise
66
Exercise
67
resume()
68
resume()
69
Difference between Sleep & Wait
70
Difference between Sleep & Wait
71
Demo Wait
72
Synchronised
73
Difference between Sleep & Wait
74
Difference between Sleep & Wait
75
Demo Join
76
Demo Without Join
77
Demo isAlive
78
Thread Priority
79
Setting Custom Thread Name
80
Setting Custom Thread Name
81
Daemon Thread
82
Daemon Thread
83
Daemon Thread
84
Daemon Thread
85
Daemon Thread
86
Thank You
87