SlideShare a Scribd company logo
1 of 50
JAVA THREADS AND
CONCURRENCY
BY NEHA KUMARI
Process
2
▰ A process has a self-contained execution environment. A process
generally has a complete, private set of basic run-time resource; in
particular, each process has its own memory space.
▰ Most implementations of the java virtual machine run as aa single
process.
Thread
▰ Threads are sometimes called lightweight processes.
Both processes and threads provide an execution
environment, but creating a new process.
▰ Threads exist within a process – every
process(application) has at least one thread.
▰ Threads share the process’s resources, including
memory and open files.
▰ Each thread is associated with an instance of the class
java.lang.Thread.
3
Threads and Processes
4
Process Process
Memory
Thread
Thread
Thread
Thread
Group
JVM(Java exe.)
Process
Operating System
Environment Variable
Multitasking and Multithreading
5
 Multitasking refers to a computer’s ability to perform multiple jobs
concurrently. Multitasking means more than one programs are running
together on a single machine.
 A thread is a single sequence of exception within a program.
 Multithreading refers to multiple threads of control within a single
program. Each program can run multiple threads of control within it, e.g.,
Web Browser.
HelloWithoutThread
public class HelloWithoutThread{
String name= null;//Keep Thread Name
Public HelloWithoutThread(String threadName){//Constructor
name=threadName;
}
Public void run(){
for(int i=0; i<50; i++){
System.out.println(i + ”Hello James ”+name);
}
}
} 6
TestWithoutThread
Public static void main(String []args){
HelloWithoutThread t1 = new HelloWithoutThread(“Java”);
HelloWithoutThread t2 = new HelloWithoutThread(“Threads”);
t1.run();
t2.run();
}
7
TestWithoutThread Output
▰ 0 Hello Java
▰ 1 Hello Java
▰ 2 Hello Java
▰ …….
▰ 48 Hello Java
▰ 49 Hello Java
▰ 0 Hello Thread
▰ 1 Hello Thread
▰ 2 Hello Thread
▰ …….
▰ 48 Hello Thread
▰ 49 Hello Thread
8
Characteristics Of Threads
▰ A Thread can create another thread.
▰ Created threads will be equally powerful.
▰ Threads need same kind of resources to be executed.
▰ Threads work concurrently.
▰ If one thread dies, other will remain active in memory.
9
Creating Threads
▰ There are two ways to create a Thread object
▻ Inherit Thread class.
▻ Implement the Runnable.
▰ In both cases the run() method should be implemented.
10
HelloWithThread
Public class HelloWithThread extends Thread{
Private String name = null;
Public HelloWithThread(String threadName){
Name = threadName;
}
Public void run(){
for(int i=0; i<500; i++){
System.out.println(i + “Hello Thread “ + name);
}
}
}
11
TestWithThread
Public static void main(String []args){
HelloWithoutThread t1 = new HelloWithoutThread(“Java”);
HelloWithoutThread t2 = new HelloWithoutThread(“C++”);
t1.run();
t2.run();
for(int i=0; i<500; i++){
System.out.println(“Main Thread”);
}
}
12
TestWithThread Output
▰ 0 Hello Thread Java
▰ 1 Hello Thread Java
▰ 2 Hello Thread Java
▰ 0 Hello Thread C++
▰ 1 Hello Thread C++
▰ 1 Hello Thread main
▰ 2 Hello Thread main
▰ 3 Hello Thread main
▰ 3 Hello Thread Java
▰ 4 Hello Thread Java
▰ 2 Hello Thread C++
▰ 3 Hello Thread C++
▰ 4 Hello Thread main
▰ ……..
▰ 48 Hello Thread Java
▰ 49 Hello Thread Java
▰ 48 Hello Thread C++
13
Scheduling Threads
14
Newly created threads
Currently executed threads
Ready queue
• Waiting for I/O operation to be
completed
• Waiting to be notified
• Sleeping
• Waiting to enter a synchronized
section.
What happens when a program with
a ServerSocket calls accept() ?
I/O operation completes
Start()
Thread State Diagram
15
Alive
new ThreadExample();
New Thread
Running
While(…) {….}
Runnable
Blocked
Dead Thread
Thread.start(); Run() method returns
Object.wait()
Thread.sleep()
Blocking IO call
Waiting on a monitor
Thread Lifecycle
stop() stop()
16
Bora
Dead
Runnable Blocked
Active
Start()
JVM
sleep(500)
wake up
suspend()
resume()
wait
notify
block on I/O
I/O available
Child of other Class-Runnable Interface
If a class is child of another class and you want to make it Thread then use Runnable interface
since Java does not support multiple inheritance.
Public class HelloThread extends Hello implements Runnable{
public void run(){
System,out,println(“Hello From Thread!”);
}
Public static void main(String args[]){
HelloThread runThread = new HelloThread();
Thread th = new Thread(run Thread);
Th.start();
}
} 17
Thread Methods
▰ Void start()
▻ Creates a new thread and make it runnable.
▻ This method can be called only once.
▰ Void run()
▻ Thee new thread begins its inside this method.
▰ Void stop() (deprecated)
▻ The thread is begin terminated.
18
Thread Methods
▰ yield()
▻ Pause the currently executing thread object and
other thread of same priority to be executed.
▰ sleep(int m)/sleep(int m, int n)
▻ The thread is slept for m milliseconds and n
nanoseconds.
19
Multiple Threads in an Application
▰ Each thread has its private run-time stack.
▰ If two threads execute the same method, each will have
its own copy of the local variables the methods uses.
▰ However, all threads see the same dynamic memory
(heap).
▰ Two different threads can act on the same object and
same static fields concurrently. 20
Green Thread
▰ Native Thread model:
▻ The threads are scheduled by the OS.
▻ Maps a single Java thread to an OS thread.
▰ Green Thread model:
▻ The threads are scheduled by the Virtual Machine.
▻ Threads are invisible to the OS.
▻ Green threads emulate multithreaded environments without relying on any active OS
capabilities.
▻ They run code in user space that manages and schedules threads
▻ Green threads enables Java to work in environments that do not have native thread
support.
▻ OS doesn’t know anything about the threads used in the VM. It’s up to the VM to
handle all the details.
21
Scheduling
▰ Thread-scheduling is the mechanism used to determine
how runnable threads are allocated CPU time.
▰ A thread-scheduling mechanism is either preemptive or
non-preemptive.
22
Preemptive Scheduling
▰ Preemptive scheduling – the thread scheduler pre-
empts(pause) a running thread and executed other thread as
per schedule.
▰ Non-preemptive scheduling – the scheduler never interrupts a
running thread. Other thread will get chance only if current
thread dies.
▰ The non-preemptive scheduler relies on the running thread to
yield control of the CPU so that other threads may execute. 23
Starvation and Livelock
▰ A non-preemptive scheduler may cause starvation.
▰ Runnable threads which are in ready queue may have to
wait to be executed for a vary long time or forever.
▰ Sometimes, starvation is also called livelock.
24
Time-sliced Scheduling
▰ Time-sliced scheduling – the scheduler allocates a
period of time that each thread can use the CPU. When
that amount of time has elapsed, the scheduler pre-
empts the thread the thread and switches to other
thread.
▰ Non time-sliced scheduler – the scheduler does not use
elapsed time to determine when to pre-empts a thread,
It used other criteria such as priority or I/O status. 25
Java Scheduling
▰ Java-scheduler is preeemptive and based on priority of
threads.
▰ It uses fixed-priority scheduling.
▰ Threads are scheduled according to their priority with
respect to other threads in the ready queue.
26
Java Scheduling
▰ The highest priority runnable thread is always selected
for execution above lower priority threads.
▰ When multiple threads have equally high priority then
only one of them will be guaranteed to be executed.
▰ Java threads are guaranteed to be preemptive-but not
time sliced.
27
Thread Priority
▰ Every thread has a priority.
▰ When a thread is created, it inherits the priority of the
thread that created it.
▰ The priority values range from 1 to 10, in increasing
priority. That means 1 is lowest and 10 is highest.
28
Thread Priority
▰ The priority can be adjusted subsequently using the
setPriority(5) method.
▰ The priority of a thread may be obtained using getPriority().
▰ Priority constants are defined in Thread class:
▻ MIN_PRIORITY = 1
▻ MAX_PRIORITY = 10
▻ NORM_PRIORITY = 5
▰ Thread th = new Thread(“Raina”);
▻ Th.setPriority(4);
29
Some Notes
▰ Thread implantation in Java is actually based on
operating system support.
▰ Some Windows operating systems support only 7
priority levels, so mapped to the same operating
system level.
30
Dameon Threads
▰ Dameon threads are “background” threads, that provide
services to other threads, e.g., the garbage collection
thread.
▰ The Java VM will not exit if non-Daemon threads are
executing.
▰ Daemon threads will die when the Java VM exits.
▰ t.setDaemon(true) 31
Thread Group
▰ The ThreadGroup class is used to create
groups of similar threads.
32
ThreadInfo
Public class ThreadInfo {
Public static void main(String []args){
Thread t = new Thread(“My Thread”);
log(“”,t) ;
}
Public static void log(String indent, Thread t){
System.out.println(indent + “THREAD Name:” + t.getName());
System.out.println(indent + “ID :” + t.getId());
System.out.println(indent + “Priority :” + t.getPriority());
System.out.println(indent + “State :” + t,getState());
System.out.println(indent + “Thread Group :” + t.getThreadGroup().getName());
System.out.println(indent + “Is Alive :” + t,isAlive());
System.out.println(indent + “Is Daemon :” + t.isDaemon() + “n”);
}
}
33
ThreadInfo
Public static void info(String indent, ThreadGroup tg){
int threadCount = tg.activeCount(); //Get Active Thread Count
Thread[] threads = new Thread[threadedCount];
tg.enumerate(threads); //Get Active Threads
System.out.println(indent + “THREAD GROUP NAME: “ + tg.getName());
System.out.println(indent + “Is Daemon : “ + tg.isDaemon());
//Log Threads Details
for(int I = 0; I < threads.length(); i++){
log(indent + “t” , threads[i]);
}
int groupCount = tg.activeGroupCount(); //Get Active ThreadGroup Count
ThreadGroup[] groups = new ThreadGroup[groupCount];
tg.enumerate(groups); //Get ThreadGroups
for(int i = 0; i < groups.length; i++){
info(indent + “t”, groups[i]);
}}
34
ThreadInfo
Public static void main(String[] args) throws Exception{
Thread t = new Thread.currentThread(); //Get Current Thread
ThreadGroup tg = t.getThreadGroup();
While(tg.getParent() !=null){ //Get Root ThreadGRoup
Tg = tg.getParent();
}
HelloWithThread t1 = new HelloWithThread(“Traina”);
T1.setPriority(1);
HelloWithThread t2 = new HelloWithThread(“Yuvraj”);
T2.setPriority(1);
T1.start();
t2,.start();
Info(“”,tg);
}
35
Concurrency
▰ An object in a program can be changed by more than
one threads concurrently.
▰ Q. Is the order of changes that were performed on the
object important?
36
Race Condition
▰ When two threads are simultaneously modifying a
single object, is called race-condition.
▰ Both threads “race” to store their values in a single
object.
▰ The outcome of a program is affected by the order in
which the program’s threads are allocated CPU time.
37
Deposit in an Account
38
User 1 User 2
Account
Deposit in an Account
Balance = 1000
getBalance(); 1000
setBalance(2000)
getBalance(); 1000
setBalance(2000)
Balance = 2000
Synchronized access
39
User 1 User 2
Account
Deposit in an Account
Balance = 1000
getBalance(); 1000
setBalance(2000)
getBalance(); 2000
setBalance(3000)
Balance = 3000
Instance vs static attributes
40
instance
static
instance
static
Name = A
Address = Add11
1010
Name = B
Address = Add2
1011
+getName()
+getAddress()
$ getAveAge()
AVR_AGE = 60
Person
-name : String
-address : String
$ AVR_AGE :int = 60
+getName()
+getAddress()
$ getAveAge()
Class Methods
Attributes
1011
2B
p1
p2
1010
2B
Person p1,p2
P1 = new Person()
P2 = new Person()
P1.getName()
P2.getAvrAge()
Person.getAvrAge()
Account
Public class Account{
private int balance = 0;
public void deposit(String message. Int amount){
int bal = getBalance();
System.out.println(message + “Now Balance is “ +
getBalance());
}
public int getBalance(){
try{
thread.sleep(200); //simulate Database Operation
}catch(InterrruptedException e){
return balance;
}
41
Account
public void setBalance(int balance){
Try{
Thread.sleep(200); //simulate Database Operation
}catch (InterruptedException e) {}
this.balance = balance;
}
42
RacingCondThread
Public class RacingCondThread extends Thread{
public static Account data = new Account();
String name = null;
public RacingCondThread(String name){
this.name = name;
}
public void run(){
for(int i=0; i<5; i++){
data.deposit(name,1000);
}
} 43
RacingCondThread
Public static void main(String[] args){
RacinfCondThread t1 = new RacingCondThread(“Raina”);
RacingCondThread t2 = new RacingCondThread(“Virat”);
t1.start();
t2.start();
}
44
Account - synchronized
Public class Account{
private int balance = 0;
public synchronized void deposit(String message, int amount){
int bal = getBalance() + amount;
setBalance(getBalance() + amount);
System.out.println(message + “Now Bal is” + bal);
}
//…..
} 45
Monitor Keys
46
Thread 1
Thread 2
Static Sync Methods
x
z
y
Instance Sync Methods
b
a
c
X() Class
Monitor
B()
y()
a() Object
Monitor
Synchronization types
▰ Method
Public synchronized void deposit(String message, int amount){……
▰ Block
Public void deposit(String message, int amount){
synchronized (this){
int bal = getBalance() + amount, setBalance(bal);
}
System.out.println(message + “Now Bal is” + bal);
} 47
Monitors
▰ Each object has a “monitor” that is a token used to
determine which application thread has control of a
particular object.
▰ Access to the object monitor is queued.
▰ There are two monitors:
▻ One for synchronized instance methods called
Object Monitor.
▻ Other for synchronized static methods called Class
Monitor. 48
Disclaimer
▰ This is an educational presentation to enhance the skill of
computer science students.
▰ This presentation is available for free to computer science
students.
▰ Some internet images from different URLs are used int his
presentation to simplify technical examples and correlate
examples with the real world.
▰ We are grateful to owners of these URLs and pictures. 49
Thank You!
Happy Learning...
50

More Related Content

Similar to Java Threads And Concurrency Presentation. 2024

Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in javaElizabeth alexander
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfGouthamSoma1
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languagearnavytstudio2814
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight ProcessesIsuru Perera
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Java multithreading
Java multithreadingJava multithreading
Java multithreadingMohammed625
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Multithreading
MultithreadingMultithreading
MultithreadingF K
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javajunnubabu
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 

Similar to Java Threads And Concurrency Presentation. 2024 (20)

Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Java
JavaJava
Java
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
multithreading
multithreadingmultithreading
multithreading
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Java
JavaJava
Java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 

Recently uploaded

DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 

Recently uploaded (20)

DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 

Java Threads And Concurrency Presentation. 2024

  • 2. Process 2 ▰ A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resource; in particular, each process has its own memory space. ▰ Most implementations of the java virtual machine run as aa single process.
  • 3. Thread ▰ Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new process. ▰ Threads exist within a process – every process(application) has at least one thread. ▰ Threads share the process’s resources, including memory and open files. ▰ Each thread is associated with an instance of the class java.lang.Thread. 3
  • 4. Threads and Processes 4 Process Process Memory Thread Thread Thread Thread Group JVM(Java exe.) Process Operating System Environment Variable
  • 5. Multitasking and Multithreading 5  Multitasking refers to a computer’s ability to perform multiple jobs concurrently. Multitasking means more than one programs are running together on a single machine.  A thread is a single sequence of exception within a program.  Multithreading refers to multiple threads of control within a single program. Each program can run multiple threads of control within it, e.g., Web Browser.
  • 6. HelloWithoutThread public class HelloWithoutThread{ String name= null;//Keep Thread Name Public HelloWithoutThread(String threadName){//Constructor name=threadName; } Public void run(){ for(int i=0; i<50; i++){ System.out.println(i + ”Hello James ”+name); } } } 6
  • 7. TestWithoutThread Public static void main(String []args){ HelloWithoutThread t1 = new HelloWithoutThread(“Java”); HelloWithoutThread t2 = new HelloWithoutThread(“Threads”); t1.run(); t2.run(); } 7
  • 8. TestWithoutThread Output ▰ 0 Hello Java ▰ 1 Hello Java ▰ 2 Hello Java ▰ ……. ▰ 48 Hello Java ▰ 49 Hello Java ▰ 0 Hello Thread ▰ 1 Hello Thread ▰ 2 Hello Thread ▰ ……. ▰ 48 Hello Thread ▰ 49 Hello Thread 8
  • 9. Characteristics Of Threads ▰ A Thread can create another thread. ▰ Created threads will be equally powerful. ▰ Threads need same kind of resources to be executed. ▰ Threads work concurrently. ▰ If one thread dies, other will remain active in memory. 9
  • 10. Creating Threads ▰ There are two ways to create a Thread object ▻ Inherit Thread class. ▻ Implement the Runnable. ▰ In both cases the run() method should be implemented. 10
  • 11. HelloWithThread Public class HelloWithThread extends Thread{ Private String name = null; Public HelloWithThread(String threadName){ Name = threadName; } Public void run(){ for(int i=0; i<500; i++){ System.out.println(i + “Hello Thread “ + name); } } } 11
  • 12. TestWithThread Public static void main(String []args){ HelloWithoutThread t1 = new HelloWithoutThread(“Java”); HelloWithoutThread t2 = new HelloWithoutThread(“C++”); t1.run(); t2.run(); for(int i=0; i<500; i++){ System.out.println(“Main Thread”); } } 12
  • 13. TestWithThread Output ▰ 0 Hello Thread Java ▰ 1 Hello Thread Java ▰ 2 Hello Thread Java ▰ 0 Hello Thread C++ ▰ 1 Hello Thread C++ ▰ 1 Hello Thread main ▰ 2 Hello Thread main ▰ 3 Hello Thread main ▰ 3 Hello Thread Java ▰ 4 Hello Thread Java ▰ 2 Hello Thread C++ ▰ 3 Hello Thread C++ ▰ 4 Hello Thread main ▰ …….. ▰ 48 Hello Thread Java ▰ 49 Hello Thread Java ▰ 48 Hello Thread C++ 13
  • 14. Scheduling Threads 14 Newly created threads Currently executed threads Ready queue • Waiting for I/O operation to be completed • Waiting to be notified • Sleeping • Waiting to enter a synchronized section. What happens when a program with a ServerSocket calls accept() ? I/O operation completes Start()
  • 15. Thread State Diagram 15 Alive new ThreadExample(); New Thread Running While(…) {….} Runnable Blocked Dead Thread Thread.start(); Run() method returns Object.wait() Thread.sleep() Blocking IO call Waiting on a monitor
  • 16. Thread Lifecycle stop() stop() 16 Bora Dead Runnable Blocked Active Start() JVM sleep(500) wake up suspend() resume() wait notify block on I/O I/O available
  • 17. Child of other Class-Runnable Interface If a class is child of another class and you want to make it Thread then use Runnable interface since Java does not support multiple inheritance. Public class HelloThread extends Hello implements Runnable{ public void run(){ System,out,println(“Hello From Thread!”); } Public static void main(String args[]){ HelloThread runThread = new HelloThread(); Thread th = new Thread(run Thread); Th.start(); } } 17
  • 18. Thread Methods ▰ Void start() ▻ Creates a new thread and make it runnable. ▻ This method can be called only once. ▰ Void run() ▻ Thee new thread begins its inside this method. ▰ Void stop() (deprecated) ▻ The thread is begin terminated. 18
  • 19. Thread Methods ▰ yield() ▻ Pause the currently executing thread object and other thread of same priority to be executed. ▰ sleep(int m)/sleep(int m, int n) ▻ The thread is slept for m milliseconds and n nanoseconds. 19
  • 20. Multiple Threads in an Application ▰ Each thread has its private run-time stack. ▰ If two threads execute the same method, each will have its own copy of the local variables the methods uses. ▰ However, all threads see the same dynamic memory (heap). ▰ Two different threads can act on the same object and same static fields concurrently. 20
  • 21. Green Thread ▰ Native Thread model: ▻ The threads are scheduled by the OS. ▻ Maps a single Java thread to an OS thread. ▰ Green Thread model: ▻ The threads are scheduled by the Virtual Machine. ▻ Threads are invisible to the OS. ▻ Green threads emulate multithreaded environments without relying on any active OS capabilities. ▻ They run code in user space that manages and schedules threads ▻ Green threads enables Java to work in environments that do not have native thread support. ▻ OS doesn’t know anything about the threads used in the VM. It’s up to the VM to handle all the details. 21
  • 22. Scheduling ▰ Thread-scheduling is the mechanism used to determine how runnable threads are allocated CPU time. ▰ A thread-scheduling mechanism is either preemptive or non-preemptive. 22
  • 23. Preemptive Scheduling ▰ Preemptive scheduling – the thread scheduler pre- empts(pause) a running thread and executed other thread as per schedule. ▰ Non-preemptive scheduling – the scheduler never interrupts a running thread. Other thread will get chance only if current thread dies. ▰ The non-preemptive scheduler relies on the running thread to yield control of the CPU so that other threads may execute. 23
  • 24. Starvation and Livelock ▰ A non-preemptive scheduler may cause starvation. ▰ Runnable threads which are in ready queue may have to wait to be executed for a vary long time or forever. ▰ Sometimes, starvation is also called livelock. 24
  • 25. Time-sliced Scheduling ▰ Time-sliced scheduling – the scheduler allocates a period of time that each thread can use the CPU. When that amount of time has elapsed, the scheduler pre- empts the thread the thread and switches to other thread. ▰ Non time-sliced scheduler – the scheduler does not use elapsed time to determine when to pre-empts a thread, It used other criteria such as priority or I/O status. 25
  • 26. Java Scheduling ▰ Java-scheduler is preeemptive and based on priority of threads. ▰ It uses fixed-priority scheduling. ▰ Threads are scheduled according to their priority with respect to other threads in the ready queue. 26
  • 27. Java Scheduling ▰ The highest priority runnable thread is always selected for execution above lower priority threads. ▰ When multiple threads have equally high priority then only one of them will be guaranteed to be executed. ▰ Java threads are guaranteed to be preemptive-but not time sliced. 27
  • 28. Thread Priority ▰ Every thread has a priority. ▰ When a thread is created, it inherits the priority of the thread that created it. ▰ The priority values range from 1 to 10, in increasing priority. That means 1 is lowest and 10 is highest. 28
  • 29. Thread Priority ▰ The priority can be adjusted subsequently using the setPriority(5) method. ▰ The priority of a thread may be obtained using getPriority(). ▰ Priority constants are defined in Thread class: ▻ MIN_PRIORITY = 1 ▻ MAX_PRIORITY = 10 ▻ NORM_PRIORITY = 5 ▰ Thread th = new Thread(“Raina”); ▻ Th.setPriority(4); 29
  • 30. Some Notes ▰ Thread implantation in Java is actually based on operating system support. ▰ Some Windows operating systems support only 7 priority levels, so mapped to the same operating system level. 30
  • 31. Dameon Threads ▰ Dameon threads are “background” threads, that provide services to other threads, e.g., the garbage collection thread. ▰ The Java VM will not exit if non-Daemon threads are executing. ▰ Daemon threads will die when the Java VM exits. ▰ t.setDaemon(true) 31
  • 32. Thread Group ▰ The ThreadGroup class is used to create groups of similar threads. 32
  • 33. ThreadInfo Public class ThreadInfo { Public static void main(String []args){ Thread t = new Thread(“My Thread”); log(“”,t) ; } Public static void log(String indent, Thread t){ System.out.println(indent + “THREAD Name:” + t.getName()); System.out.println(indent + “ID :” + t.getId()); System.out.println(indent + “Priority :” + t.getPriority()); System.out.println(indent + “State :” + t,getState()); System.out.println(indent + “Thread Group :” + t.getThreadGroup().getName()); System.out.println(indent + “Is Alive :” + t,isAlive()); System.out.println(indent + “Is Daemon :” + t.isDaemon() + “n”); } } 33
  • 34. ThreadInfo Public static void info(String indent, ThreadGroup tg){ int threadCount = tg.activeCount(); //Get Active Thread Count Thread[] threads = new Thread[threadedCount]; tg.enumerate(threads); //Get Active Threads System.out.println(indent + “THREAD GROUP NAME: “ + tg.getName()); System.out.println(indent + “Is Daemon : “ + tg.isDaemon()); //Log Threads Details for(int I = 0; I < threads.length(); i++){ log(indent + “t” , threads[i]); } int groupCount = tg.activeGroupCount(); //Get Active ThreadGroup Count ThreadGroup[] groups = new ThreadGroup[groupCount]; tg.enumerate(groups); //Get ThreadGroups for(int i = 0; i < groups.length; i++){ info(indent + “t”, groups[i]); }} 34
  • 35. ThreadInfo Public static void main(String[] args) throws Exception{ Thread t = new Thread.currentThread(); //Get Current Thread ThreadGroup tg = t.getThreadGroup(); While(tg.getParent() !=null){ //Get Root ThreadGRoup Tg = tg.getParent(); } HelloWithThread t1 = new HelloWithThread(“Traina”); T1.setPriority(1); HelloWithThread t2 = new HelloWithThread(“Yuvraj”); T2.setPriority(1); T1.start(); t2,.start(); Info(“”,tg); } 35
  • 36. Concurrency ▰ An object in a program can be changed by more than one threads concurrently. ▰ Q. Is the order of changes that were performed on the object important? 36
  • 37. Race Condition ▰ When two threads are simultaneously modifying a single object, is called race-condition. ▰ Both threads “race” to store their values in a single object. ▰ The outcome of a program is affected by the order in which the program’s threads are allocated CPU time. 37
  • 38. Deposit in an Account 38 User 1 User 2 Account Deposit in an Account Balance = 1000 getBalance(); 1000 setBalance(2000) getBalance(); 1000 setBalance(2000) Balance = 2000
  • 39. Synchronized access 39 User 1 User 2 Account Deposit in an Account Balance = 1000 getBalance(); 1000 setBalance(2000) getBalance(); 2000 setBalance(3000) Balance = 3000
  • 40. Instance vs static attributes 40 instance static instance static Name = A Address = Add11 1010 Name = B Address = Add2 1011 +getName() +getAddress() $ getAveAge() AVR_AGE = 60 Person -name : String -address : String $ AVR_AGE :int = 60 +getName() +getAddress() $ getAveAge() Class Methods Attributes 1011 2B p1 p2 1010 2B Person p1,p2 P1 = new Person() P2 = new Person() P1.getName() P2.getAvrAge() Person.getAvrAge()
  • 41. Account Public class Account{ private int balance = 0; public void deposit(String message. Int amount){ int bal = getBalance(); System.out.println(message + “Now Balance is “ + getBalance()); } public int getBalance(){ try{ thread.sleep(200); //simulate Database Operation }catch(InterrruptedException e){ return balance; } 41
  • 42. Account public void setBalance(int balance){ Try{ Thread.sleep(200); //simulate Database Operation }catch (InterruptedException e) {} this.balance = balance; } 42
  • 43. RacingCondThread Public class RacingCondThread extends Thread{ public static Account data = new Account(); String name = null; public RacingCondThread(String name){ this.name = name; } public void run(){ for(int i=0; i<5; i++){ data.deposit(name,1000); } } 43
  • 44. RacingCondThread Public static void main(String[] args){ RacinfCondThread t1 = new RacingCondThread(“Raina”); RacingCondThread t2 = new RacingCondThread(“Virat”); t1.start(); t2.start(); } 44
  • 45. Account - synchronized Public class Account{ private int balance = 0; public synchronized void deposit(String message, int amount){ int bal = getBalance() + amount; setBalance(getBalance() + amount); System.out.println(message + “Now Bal is” + bal); } //….. } 45
  • 46. Monitor Keys 46 Thread 1 Thread 2 Static Sync Methods x z y Instance Sync Methods b a c X() Class Monitor B() y() a() Object Monitor
  • 47. Synchronization types ▰ Method Public synchronized void deposit(String message, int amount){…… ▰ Block Public void deposit(String message, int amount){ synchronized (this){ int bal = getBalance() + amount, setBalance(bal); } System.out.println(message + “Now Bal is” + bal); } 47
  • 48. Monitors ▰ Each object has a “monitor” that is a token used to determine which application thread has control of a particular object. ▰ Access to the object monitor is queued. ▰ There are two monitors: ▻ One for synchronized instance methods called Object Monitor. ▻ Other for synchronized static methods called Class Monitor. 48
  • 49. Disclaimer ▰ This is an educational presentation to enhance the skill of computer science students. ▰ This presentation is available for free to computer science students. ▰ Some internet images from different URLs are used int his presentation to simplify technical examples and correlate examples with the real world. ▰ We are grateful to owners of these URLs and pictures. 49