0% found this document useful (0 votes)
7 views

Module_3_Threads

The document provides an overview of Java programming concepts related to threads, including thread states, creation methods, and thread synchronization. It explains the lifecycle of threads, their various states, and the importance of managing concurrency to avoid unpredictable outcomes. Additionally, it covers thread priority and synchronization techniques to ensure safe access to shared resources in multi-threaded applications.

Uploaded by

halaplay385
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Module_3_Threads

The document provides an overview of Java programming concepts related to threads, including thread states, creation methods, and thread synchronization. It explains the lifecycle of threads, their various states, and the importance of managing concurrency to avoid unpredictable outcomes. Additionally, it covers thread priority and synchronization techniques to ensure safe access to shared resources in multi-threaded applications.

Uploaded by

halaplay385
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Course Title: Java Programming

Course Code: E1UA307C


Java Programming
Module 3
Threads - Thread states -
Thread priority - Thread operations – Thread Synchronization
Threads
• Thread can be defined as a subprocess with lightweight with the smallest unit of processes and also has
separate paths of execution.
• The main advantage of multiple threads is efficiency (allowing multiple things at the same time). For
example, in MS Word. one thread automatically formats the document while another thread is taking
user input.
• Another advantage is quick response, if we use multiple threads in a process and if a thread gets stuck
due to lack of resources or an exception, the other threads can continue to execution, allowing the
process (which represents an application) to continue to be responsive.

2
Threads States or Life Cycle Of Thread
• A thread in Java at any point of time exists in any one of the following states. A thread lies only in one
of the states at any instant:
1. New State
2. Active State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State

3
Threads states
• There are multiple states of the thread in a lifecycle as mentioned below:
• New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run
when the thread is in this state. When a thread lies in the new state, its code is yet to be run and hasn’t
started to execute.
• Active State: A Thread that is a new state by default gets transferred to Active state when it invokes
the start() method, his Active state contains two sub-states namely:
• Runnable State: A thread in the runnable state is prepared to execute the code. When a new thread's
start() method is called, it enters a runnable state. In the runnable environment, the thread is ready for
execution and is awaiting the processor's availability (CPU time). That is, the thread has entered the
queue (line) of threads waiting for execution.
• Running State: When the Thread Receives CPU allocated by Thread Scheduler, it transfers from the
“Runnable” state to the “Running” state, and after the expiry of its given time slice session, it again
moves back to the “Runnable” state and waits for its next time slice.
• Blocked: The thread will be in blocked state when it is trying to acquire a lock (CPU) but currently the
lock (CPU) is acquired by the other thread. The thread will move from the blocked state to runnable
state when it acquires the lock.

4
Threads States
• Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will
move to the runnable state when other thread will notify or that thread will be terminated.
• Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out
parameter. A thread lies in this state until the timeout is completed or until a notification is received.
For example, when a thread calls sleep or a conditional wait, it is moved to a timed waiting state.
• Terminated State: A thread terminates because of either of the following reasons:
• Because it exits normally. This happens when the code of the thread has been entirely executed by
the program.
• Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled
exception.

5
How to create a thread in Java
• There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

1. By Extending Thread Class


We can run Threads in Java by using Thread Class, which provides constructors and methods for creating
and performing operations on a Thread, which extends a Thread class that can implement Runnable
Interface.
Commonly used Constructors of Thread class:
3. Thread()
4. Thread(Runnable r)
5. Thread(String name)
6. Thread(Runnable r, String name)

6
Threads
• Example:

class Main extends Thread {


// initiated run method for Thread
public void run()
{
System.out.println("Thread Started Running...");
}
public static void main(String[] args)
{
Main g1 = new Main();
// Invoking Thread using start() method
g1.start();
}
}

7
Commonly used methods of Thread class:
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread. JVM calls the run() method on the thread.
• public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
• public void join(): waits for a thread to die.
• public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the thread.
• public Thread currentThread(): returns the reference of currently executing thread.
• public int getId(): returns the id of the thread.

8
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void setDaemon(boolean b): marks the thread as daemon or user thread.
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the thread has been interrupted.
• public static boolean interrupted(): tests if the current thread has been interrupted.

9
2. By implementing Runnable interface:

public class Main implements Runnable {


public static void main(String[] args) {
Runnable obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
} Output:
This code is outside of the thread
This code is running in a thread
10
3. Using the Thread Class: Thread(String Name):
public class Main {
public static void main(String args[])
{
// Thread object created and initiated with data
Thread t = new Thread("My first thread");
// Thread gets started
t.start();
// getting data of Thread through String
String s = t.getName();
System.out.println(s);
}
}

11
4) Using the Thread Class: Thread(Runnable r, String name):

public class Main implements Runnable


{
public void run()
{
System.out.println("Now the thread is running ...");
}
public static void main(String args[])
{
// creating an object of the class Main
Runnable r1 = new Main();
// creating an object of the class Thread using Thread(Runnable r, String
name)
Thread th1 = new Thread(r1, "My new thread");
// the start() method moves the thread to the active state
th1.start();
// getting the thread name by invoking the getName() method
String str = th1.getName(); Output:
System.out.println(str); My new thread
}} Now the thread is running12 ...
Concurrency Problems
• Because threads run at the same time as other parts of the program, there is no way to know in which
order the code will run.
• When the threads and main program are reading and writing the same variables, the values are
unpredictable. The problems that result from this are called concurrency problems.
Example: A code example where the value of the variable amount is unpredictable:
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println(amount); Output: (may be)
amount++; 0
System.out.println(amount); 2
}
public void run() { OR
0
amount++;
1
}}
13
• To avoid concurrency problems, one possible solution is to use the isAlive() method of the thread to
check whether the thread has finished running before using any attributes that the thread can change.
Example
Use isAlive() to prevent concurrency problems:
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
thread.start();
while(thread.isAlive()) {
System.out.println("Waiting...");
}
System.out.println(amount);
amount++;
System.out.println(amount);
}
public void run() { Output:
amount++; Waiting...
} 1
} 2
14
Thread priority
• Each thread has a priority.
• Java works within a multithreading environment in which thread scheduler assigns the processor to a
thread based on the priority of thread.
• Whenever we create a thread in Java, it always has some priority assigned to it.
• Priority can either be given by JVM while creating the thread or it can be given by the programmer
explicitly.
• Priorities are represented by a number between 1 and 10. In most cases, the thread scheduler schedules
the threads according to their priority (known as preemptive scheduling).
• 3 constants are defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

• Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the


value of MAX_PRIORITY is 10.
15
• We will use currentThread() method to get the name of the current thread.
• User can also use setName() method if he/she wants to make names of thread as per choice for
understanding purposes.
• getName() method will be used to get the name of the thread.
• The accepted value of priority for a thread is in the range of 1 to 10.

Let us do discuss how to get and set priority of a thread in java:

1. public final int getPriority(): java.lang.Thread.getPriority() method returns priority of given


thread.

2. public final void setPriority(int newPriority): java.lang.Thread.setPriority() method changes the


priority of thread to the value newPriority. This method throws IllegalArgumentException if value of
parameter newPriority goes beyond minimum(1) and maximum(10) limit.
16
Example
class MyThread extends Thread {
public void run()
{ System.out.println("Inside run method");
}
public static void main(String[] args) Output:
{ // Creating random threads t1 thread priority : 5
MyThread t1 = new MyThread();
t2 thread priority : 5
MyThread t2 = new MyThread();
MyThread t3 = new MyThread(); t3 thread priority : 5
System.out.println("t1 thread priority : "+ t1.getPriority()); t1 thread priority : 2
System.out.println("t2 thread priority : "+ t2.getPriority()); t2 thread priority : 5
System.out.println("t3 thread priority : "+ t3.getPriority()); t3 thread priority : 8
// Setting priorities of threads by passing integer arguments
Currently Executing Thread :
t1.setPriority(2);
t2.setPriority(5); main
t3.setPriority(8); Main thread priority : 5
// t3.setPriority(21); will throw IllegalArgumentException Main thread priority : 10
System.out.println("t1 thread priority : "+ t1.getPriority());
System.out.println("t2 thread priority : "+ t2.getPriority());
System.out.println("t3 thread priority : "+ t3.getPriority());
// Main thread // Displays the name of currently executing Thread
System.out.println("Currently Executing Thread : "+ Thread.currentThread().getName());
System.out.println("Main thread priority : "+ Thread.currentThread().getPriority());
// Main thread priority is set to 10
Thread.currentThread().setPriority(10);
17
System.out.println("Main thread priority : "+ Thread.currentThread().getPriority());
Example 2
Child thread Getting Same Priority as Parent thread:
class MyThread extends Thread {
public void run()
{ System.out.println("Inside run method");
}
public static void main(String[] args)
{ // Creating random threads
Thread.currentThread().setPriority(10);
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
System.out.println("t1 thread priority : "+ t1.getPriority());
System.out.println("t2 thread priority : "+ t2.getPriority());
System.out.println("t3 thread priority : "+ t3.getPriority());
System.out.println("Main thread priority : "+
Thread.currentThread().getPriority());
} }
Output:
t1 thread priority : 10
t2 thread priority : 10
t3 thread priority : 10
Main thread priority : 10
18
getId in Multithreading
class MultithreadingDemo extends Thread {
public void run()
{
System.out.println("Thread " + Thread.currentThread().getId()+ " is running");
}}
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) { Output:
MultithreadingDemo object= new MultithreadingDemo(); Thread 11 is running
object.start(); Thread 13 is running
}}} Thread 17 is running
Thread 16 is running
Thread 15 is running
Thread 14 is running
Thread 12 is running
Thread 18 is running
19
Thread Synchronization
• Multi-threaded programs may often come to a situation where multiple threads try to access the same
resources and finally produce erroneous and unforeseen results.
• Java thread Synchronization is used to make sure by some synchronization method that only one
thread can access the resource at a given point in time.

Thread Synchronization in Java:


• Thread Synchronization is used to coordinate and ordering of the execution of the threads in a multi-
threaded program.
• There are two types of thread synchronization are mentioned below:
1. Mutual Exclusive
2. Cooperation (Inter-thread communication in Java)

20
Mutual Exclusive:
• Mutual Exclusive helps keep threads from interfering with one another while sharing data.
• There are three types of Mutual Exclusive mentioned below:
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.

21
Understanding the problem without Synchronization
class Table{ class Main{
//method not synchronized public static void main(String
void printTable(int n){ args[]){
for(int i=1;i<=5;i++){ Table obj = new Table();//only one
System.out.println(n*i); object
try{
Thread.sleep(400); MyThread1 t1=new MyThread1(obj);
}catch(Exception e){System.out.println(e);} MyThread2 t2=new MyThread2(obj);
}}} t1.start();
class MyThread1 extends Thread{ t2.start();
Table t; }}
MyThread1(Table t){ Output:
this.t=t;
} 5
public void run(){ 100
t.printTable(5); 10
}} 200
class MyThread2 extends Thread{ 15
Table t; 300
MyThread2(Table t){
20
this.t=t;
} 400
public void run(){ 500
t.printTable(100); 25 22
}}
Java Synchronized Method
• If you declare any method as synchronized, it is known as synchronized method.
• Synchronized method is used to lock an object for any shared resource.
• When a thread invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.

23
problem solving using Synchronized Method
class Main{
class Table{ public static void main(String
//method is synchronized args[]){
synchronized void printTable(int n){
for(int i=1;i<=5;i++){ Table obj = new Table();//only one
System.out.println(n*i); object
try{ MyThread1 t1=new MyThread1(obj);
Thread.sleep(400); MyThread2 t2=new MyThread2(obj);
}catch(Exception e){System.out.println(e);} t1.start();
}}} t2.start();
class MyThread1 extends Thread{
}}
Table t;
MyThread1(Table t){ Output:
this.t=t; 5
} 10
public void run(){ 15
t.printTable(5); 20
}}
25
class MyThread2 extends Thread{
Table t; 100
MyThread2(Table t){ 200
this.t=t; 300
} 400
public void run(){ 500 24
t.printTable(100);
Synchronized Block in Java
• Synchronized block can be used to perform synchronization on any specific resource of the method.
• Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in such
cases, we can use synchronized block.
• If we put all the codes of the method in the synchronized block, it will work same as the synchronized
method.
Points to Remember:
• Synchronized block is used to lock an object for any shared resource.
• Scope of synchronized block is smaller than the method.
• A Java synchronized block doesn't allow more than one JVM, to provide access control to a shared
resource.
• The system performance may degrade because of the slower working of synchronized keyword.
• Java synchronized block is more efficient than Java synchronized method.
Syntax:
synchronized (objectidentifier) {
//code block
} 25
problem solving using Synchronized Block
class Table{ class Main{
void printTable(int n){
public static void main(String args[])
for(int i=1;i<=5;i++){
System.out.println(n*i);
{
try{ Table obj = new Table();//only one
Thread.sleep(400); object
}catch(Exception e){System.out.println(e);} MyThread1 t1=new MyThread1(obj);
}}}
MyThread2 t2=new MyThread2(obj);
class MyThread1 extends Thread{
Table t; t1.start();
MyThread1(Table t){ t2.start();
this.t=t; }}
} Output:
public void run(){ 5
synchronized(t) {
10
t.printTable(5);
}}} 15
class MyThread2 extends Thread{ 20
Table t; 25
MyThread2(Table t){ 100
this.t=t;
}
200
public void run(){ 300
synchronized(t) { 400
t.printTable(100); 500 26
}}}
Static Synchronization
• If you make any static method as synchronized, the lock will be on the class not on object.

27
problem solving using Static Synchronized
class Table{ class Main{
synchronized static void printTable(int n){ public static void main(String args[]){
for(int i=1;i<=5;i++){ //Table obj = new Table();//only one
System.out.println(n*i); object
try{ MyThread1 t1=new MyThread1();
Thread.sleep(400); MyThread2 t2=new MyThread2();
}catch(Exception e){System.out.println(e);} t1.start();
}}} t2.start();
class MyThread1 extends Thread{ }}
Output:
public void run(){ 5
Table.printTable(5); 10
}} 15
class MyThread2 extends Thread{ 20
public void run(){ 25
Table.printTable(100); 100
200
}}
300
400
500 28
Inter Thread Communication
• Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
• Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.
• It is implemented by following methods of Object class:
1. wait()
2. notify()
3. notifyAll()

29
1) wait() method:
• The wait() method causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount of time
has elapsed.
Method Description
public final void wait()throws
It waits until object is notified.
InterruptedException
public final void wait(long
It waits for the specified amount of
timeout)throws
time.
InterruptedException

2) notify() method
• The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened.
Syntax:
public final void notify()
30
3) notifyAll() method:
• Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()

31
Example
class Chat { class T1 implements Runnable {
boolean flag = false; Chat m;
public synchronized void Question(String msg) {
String[] s1 = { "Hi", "How are you ?",
if (flag) {
try { "I am also doing fine!" };
wait(); public T1(Chat m1) {
} catch (InterruptedException e) { this.m = m1;
e.printStackTrace(); }
}} public void run() {
System.out.println(msg); for (int i = 0; i < s1.length; i++) {
flag = true; m.Question(s1[i]);
notify(); }}}
}
class T2 implements Runnable {
public synchronized void Answer(String msg) {
if (!flag) { Chat m;
try { String[] s2 = { "Hi", "I am good, what about
wait(); you?",
} catch (InterruptedException e) { "Great!" };
e.printStackTrace(); public T2(Chat m2) {
}} this.m = m2;
System.out.println(msg); }
flag = false; public void run() {
notify();
for (int i = 0; i < s2.length; i++) {
}}
m.Answer(s2[i]);
}}} 32
public class MyThread {
public static void main(String[] args) {
Chat m = new Chat();
Runnable obj1= new T1(m);
Runnable obj2= new T2(m);
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start(); Output:

} Hi
} Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!

33
d
• If

34
d
• If

35

You might also like