SlideShare a Scribd company logo
Lecture 04
Chapter 7: Threads
(35 slides- 2 slots)
Why should you study this chapter?
 This chapter will help you developing a program in
which some tasks executing concurrently.
 Nowadays, in one program, some tasks execute
concurrently. You usually saw them in a web page
including texts, sounds, images, games, …
changing concurrently.
 Nowadays, operating systems (OS) support many
programs running concurrently.
 Open the Task Manager of Windows OS (Ctrl Alt
Delete) to see how many programs are running in
your computer.
2
Review
Previous lecture:
 Introduction to OO Paradigm
 Benefits of OO Implementation
 Hints for class design
 Declaring/ Using classes/ abstract classes/
Interfaces/ Anonymous classes/ Enum types
3
Objectives
 Definitions: Process, thread.
 Multi-Processing System and Multi-Threading
Program.
 What are threads.
 Thread Fundamentals in Java
 Monitors, Waiting and Notifying
Your homework:
Workshop 3 (with report): The producer-consumer
problem and the philosophers problem.
Workshop 4 (with report): Deadlock application. Refer
to the source code in the page 236 of the book
Complete Java 2 Certification. Explain why the
application causes deadlock.
Assessment: the next class.
4
1- Definitions
 Program-chương trình: An executable
file (data + code) stored in secondary
memory(disk).
 Process- tiến trình: A program in
running. It’s data and code are loaded
to RAM in a contiguous memory block.
 Thread- luồng: is a smallest unit code
(function/method) in an application that
performs a special job. An application
can contain some threads. A thread
can be called as lightweight process.
Data
Code
Thread 1
Thread 2
Thread 3
5
7.1- Processes and Multi
Processing System
 A process has a self-contained execution environment. A
process generally has a complete, private set of basic run-
time resources; in particular, each process has its own
memory space.
 Multi Processing/ Multi Tasking System: Almost of operating
systems allows many processes executing concurrently.
 Open the Task Manager of Windows OS ( Ctrl+Alt+Del) to
see current processes in your computer.
 Applications tag contains processes which you start them.
 Processes tag contains processes which automatically run
immediately after the startup of OS.
6
How can OS manage concurrent
processes
Memory
App1
Code
Data
App2
Code
Data
App3
Code
Data
App Code
Addr
Duration
(mili
sec)
CP
U
…
App
1
10320 15 1
App
2
40154 17 2
App
3
80166 22 1
… … … …
… … … …
Process Table maintains information of
processes.
How does OS manage executions of processes?
Time-slicing mechanism. Each process is allocated
resources ( CPU, …) for executing in a time-slot
(such as 30 milliseconds). When the time duration
expires, this process will pause to yield resources to
the next process which will be chosen by the
scheduler of OS.7
7.2- Threads and Multi-Threading
 Threads are sometimes called lightweight processes.
Both processes and threads provide an execution
environment, but creating a new thread requires fewer
resources than creating a new process.
 Threads exist within a process — every process has
at least one thread (main thread). Threads share
the process's resources, including memory and open
files. This makes for efficient, but potentially
problematic, communication.
 Multithreaded execution is an essential feature of the
Java platform. Threads in a program are managed by
the JVM.
8
How can JVM manage threads
Memory of a
multi-thread process
App
Data
Code of thread1
Code of thread2
Code of thread3
 Thread is a smallest unit code
in an application that performs
a special job.
 A program can have several
threads they can be executed
concurrently.
Thread Code
Addr
Duratio
n
(mili
sec)
CPU State
Thread
1
10320 15 1 ready
Thread
2
40154 17 2 ready
Thread
3
80166 22 1 sleep
Thread Table maintains information of
threads
Time-slicing mechanism is used
to schedule thread executions
also.
9
Difference:
Memory
App1
Data
Code
App2
Data
Code
App3
Data
Code
Memory
App1
data
Code
Code of thread1
Code of thread2
Code of thread3
10
Race Conditions
Application
Data 1 (shared
data)
Data 2
Data 3
Thread 1
Thread 2
Thread3
Thread 4 A
race
occur
s
Need
Synchronizatio
n
Suppose that Thread2 and Thread4
concurrently execute.
Time Thread 2 Thread4
1 Data1=10 …
2 …. …
3 …. Data1= 100
4 …. …
5 … …
6 Y= Data1; …
7 …
Y=
?
11
7.3- Thread Fundamentals in Java
 Threading supports in Java:
 The java.lang.Thread class
 The java.lang.Object class
 The Java language and JVM ( Java Virtual Machine)
 How to create a thread in Java?
(1) Create a subclass of the java.lang.Thread class
and override the method run()
(2) Create a class implementing the Runnable
interface and override the run() method.
12
Threa
d
Code
Addr
State …
main 8000 run …
t 10320 run
Create a subclass of the Thread class
Thread table
Every process has
at least one thread
(main thread).
?
The start() method is implemented in the
Thread class. This method calls the
method run().
This process has 2 threads
running concurrently. At a time,
order of their execution is
decided by the scheduler.
13
Class implements the Runnable interface
Threa
d
Code
Addr
State …
main 8000 run …
t 10320 run
14
The java.lang.Thread class
Constructor
Thread()
Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)
Thread(ThreadGroup group, Runnable target)
Thread(ThreadGroup group, Runnable target,
String name)
Thread(ThreadGroup group, Runnable target,
String name, long stackSize)
Thread(ThreadGroup group, String name)
Declaration
public class Thread extends Object implements Runnable
Common Methods
start()
join ()
sleep (milisec)
yield()
notify()
notifyAll()
wait()
Properties
id
name
state
threadGroup
daemon
priority
set/get-is
15
Using some methods of the Thread class
16
Thread States
Running
BlockedSleeping
Suspende
d
Ready
Monitor
States
(JVM)
yield()
start()
(Scheduler)
sleep(milisec)
Time expired
or interrupted
Blocking method
(IO)
Blocking condition
changes or
interrupt
wait()
notify()
Ready: As soon as it is created , it can enter the running state when JVM’s
processor is assigned to it.
Running: It get full attention of JVM’s processor which executes the thread’s
run() method
Dead: When the run() method terminates.
Interrupt: A signal is sent to CPU from
IO device just after an IO operation has
terminated.Only ready threads will be
chosen by the JVM scheduler
at a time.
17
Non-race Demonstration
This program contains 2 threads:
- The first thread that will print out the system time for every second.
- The second will print out the sum of two random integers for every
half of a second.
18
Non-race Demonstration…
19
7.4- Monitors, Waiting and Notifying
 Some threads can access common resources concurrently. We
must synchronize accessing common resources  Every object
has a lock
 Lock: an extra variable is added by the compiler for monitoring
the state of common resource. Before a thread accesses the
common resource, the lock is tested.
 After a thread has the lock (it is permitted to access the common
resource), it can access common resource. When it did, it needs
notifying to others thread ( wait-notify mechanism).
Running
Seeking
Lock
waiting
Ready
Scheduler
wait()notify(),
notifyAll(),
time out, or
interrupt
Enter synchronized
code
Lock obtained
20
Monitors, Waiting and Notifying…
 Two ways to mark code as synchronize
 Synchronize an entire method: Let the synchronized
modifier in the method’s declaration.
synchronized Type Method(args){
<code>
}
 Synchronize some method of an object
Type Method ( args){
……
synchronized ( object_var){
object_var.method1(args);
object_var.method2(args);
}
}
A class
contains
synchronized
code is called
monitor.
Monitor: A technique to
encapsulate common
resources to a class.
When a thread wants to
access common
resources, it must call a
public synchronized
method. As a result,
common resources are
accessed in successive
manner.21
Demo:The Producer-Consumer Problem
- Producer makes a product then puts it to a store.
- Consumer buys a product from a store.
- Selling Procedure: First In First Out
Attention!:
Store is common resource of 2 threads: producer and consumer.
 Store is a monitor and it’s activities needs synchronization
Synchronizing:
* After a thread accessed common resource, it should sleep a moment or it
must notify to the next thread ( or all thread) in the thread-pool to awake and
execute.
* Use the synchronized keyword to declare a method that will access
common resource.
Producer
Consume
r
produc
t
produc
t
Put to the tail Get from the
head
Store
22
The Producer-Consumer Problem
/* synchronized */
No synchronization
A product is simulated as a
number.
23
The Producer-Consumer Problem
24
The Producer-Consumer Problem
25
The Producer-Consumer Problem
Synchronization is not used Synchronization is used:
26
7.5- Deadlock
What is deadlock?
Deadlock describes a
situation where two or more
threads are blocked forever,
waiting for each other  All
threads in a group halt.
When does deadlock
occur?
There exists a circular wait
the lock that is held by other
thread.
Nothing can ensure that
DEADLOCK do not occur.
27
Deadlock Demo.
28
The Philosophers Problem
Wait-Notify
Mechanism, a
way helps
preventing
deadlocks
3 classes
Deadlock!
29
The Philosophers Problem
Threa
d
Code
Addr
Duration
(mili
sec)
CP
U
State
Thread
1
10320 15 1 Suspended
Ready
Thread
2
40154 17 2 Suspended
Thread
3
80166 22 1 Suspended
… … … … ….
Thread pool
30
The Philosophers Problem
31
The Philosophers Problem
32
Summary
Concepts were introduced:
 Definitions: Program, Process, Thread
 Multi-processing system
 Multi-threading programming in Java
 Thread Fundamentals in Java
 Synchronizing access to common resource.
 Monitoring thread states: Wait-notify mechanism.
 If you want some tasks executing concurrently,
multi-threading is a solution.
33
Exercises
Workshop 3 (with report): The
producer-consumer problem and the
philosophers problem.
Workshop 4 (with report): Deadlock
application. Refer to the source code in
the page 236 of the book Complete Java
2 Certification. Explain why the
application causes deadlock.
34
Thank You
35

More Related Content

What's hot

Microkernels and Beyond
Microkernels and BeyondMicrokernels and Beyond
Microkernels and Beyond
David Evans
 
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating System
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating SystemProcess, Threads, Symmetric Multiprocessing and Microkernels in Operating System
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating SystemLieYah Daliah
 
Case Study 2: WINDOWS VISTA
Case Study 2: WINDOWS VISTACase Study 2: WINDOWS VISTA
Case Study 2: WINDOWS VISTA
Munazza-Mah-Jabeen
 
Multithreading
MultithreadingMultithreading
Multithreadingsagsharma
 
Java
JavaJava
Processes and threads
Processes and threadsProcesses and threads
Operating System Process Synchronization
Operating System Process SynchronizationOperating System Process Synchronization
Operating System Process Synchronization
Haziq Naeem
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
guesta40f80
 
Class 1: What is an Operating System?
Class 1: What is an Operating System?Class 1: What is an Operating System?
Class 1: What is an Operating System?
David Evans
 
Operating Systems 1 (7/12) - Threads
Operating Systems 1 (7/12) - ThreadsOperating Systems 1 (7/12) - Threads
Operating Systems 1 (7/12) - Threads
Peter Tröger
 
Processes and Thread OS_Tanenbaum_3e
Processes and Thread OS_Tanenbaum_3eProcesses and Thread OS_Tanenbaum_3e
Processes and Thread OS_Tanenbaum_3e
Le Gia Hoang
 
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...
vtunotesbysree
 
Slot03 concurrency2
Slot03 concurrency2Slot03 concurrency2
Slot03 concurrency2
Viên Mai
 
Os lectures
Os lecturesOs lectures
Os lectures
Adnan Ghafoor
 
VTU 5TH SEM CSE OPERATING SYSTEMS SOLVED PAPERS
VTU 5TH SEM CSE OPERATING SYSTEMS SOLVED PAPERSVTU 5TH SEM CSE OPERATING SYSTEMS SOLVED PAPERS
VTU 5TH SEM CSE OPERATING SYSTEMS SOLVED PAPERS
vtunotesbysree
 

What's hot (18)

Microkernels and Beyond
Microkernels and BeyondMicrokernels and Beyond
Microkernels and Beyond
 
Threads
ThreadsThreads
Threads
 
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating System
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating SystemProcess, Threads, Symmetric Multiprocessing and Microkernels in Operating System
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating System
 
fall2013
fall2013fall2013
fall2013
 
Case Study 2: WINDOWS VISTA
Case Study 2: WINDOWS VISTACase Study 2: WINDOWS VISTA
Case Study 2: WINDOWS VISTA
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java
JavaJava
Java
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Operating System Process Synchronization
Operating System Process SynchronizationOperating System Process Synchronization
Operating System Process Synchronization
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
 
Class 1: What is an Operating System?
Class 1: What is an Operating System?Class 1: What is an Operating System?
Class 1: What is an Operating System?
 
Operating Systems 1 (7/12) - Threads
Operating Systems 1 (7/12) - ThreadsOperating Systems 1 (7/12) - Threads
Operating Systems 1 (7/12) - Threads
 
Processes and Thread OS_Tanenbaum_3e
Processes and Thread OS_Tanenbaum_3eProcesses and Thread OS_Tanenbaum_3e
Processes and Thread OS_Tanenbaum_3e
 
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...
SOLUTION MANUAL OF OPERATING SYSTEM CONCEPTS BY ABRAHAM SILBERSCHATZ, PETER B...
 
Slot03 concurrency2
Slot03 concurrency2Slot03 concurrency2
Slot03 concurrency2
 
Os lectures
Os lecturesOs lectures
Os lectures
 
VTU 5TH SEM CSE OPERATING SYSTEMS SOLVED PAPERS
VTU 5TH SEM CSE OPERATING SYSTEMS SOLVED PAPERSVTU 5TH SEM CSE OPERATING SYSTEMS SOLVED PAPERS
VTU 5TH SEM CSE OPERATING SYSTEMS SOLVED PAPERS
 
Chapter 4 - Threads
Chapter 4 - ThreadsChapter 4 - Threads
Chapter 4 - Threads
 

Viewers also liked

Romantizam
RomantizamRomantizam
Romantizam
Marina Chudov
 
Solución pc2
Solución pc2Solución pc2
Encimera AEG HC412001GB
Encimera AEG HC412001GBEncimera AEG HC412001GB
Encimera AEG HC412001GB
Alsako Electrodomésticos
 
Derrick Washington Resume 2016 - Copy
Derrick Washington Resume 2016 - CopyDerrick Washington Resume 2016 - Copy
Derrick Washington Resume 2016 - CopyLaMont Washington
 
Universidad técnica de ambato
Universidad técnica de ambatoUniversidad técnica de ambato
Universidad técnica de ambato
Edilma Pilco
 
Evolution of the infographic: Then, now, and future-now.
Evolution of the infographic: Then, now, and future-now. Evolution of the infographic: Then, now, and future-now.
Evolution of the infographic: Then, now, and future-now.
Domo
 
Estudos intenerantes
Estudos intenerantesEstudos intenerantes
Estudos intenerantes
MariaMedeiros21
 
Inflammatory Overgrowths
Inflammatory OvergrowthsInflammatory Overgrowths
Inflammatory Overgrowths
Abeer Khasawneh
 
Solar Power Satellites
Solar Power SatellitesSolar Power Satellites
Solar Power Satellites
Mohan Patil
 
05 junit
05 junit05 junit
05 junit
mha4
 
Servicing 'Core and Chore': A framework for understanding a Modern IT Working...
Servicing 'Core and Chore': A framework for understanding a Modern IT Working...Servicing 'Core and Chore': A framework for understanding a Modern IT Working...
Servicing 'Core and Chore': A framework for understanding a Modern IT Working...
diharrison
 
The role of the central IT Services organisation in a Web 2.0 world - paper
The role of the central IT Services organisation in a Web 2.0 world - paperThe role of the central IT Services organisation in a Web 2.0 world - paper
The role of the central IT Services organisation in a Web 2.0 world - paper
diharrison
 
Ostern
Ostern Ostern
Ostern
Bett Marin
 
1 aula 6 aducao
1 aula 6   aducao1 aula 6   aducao
1 aula 6 aducao
Agamenon Manuel Cutocama
 
Ingenieros con ingenio coaching para ingenieros
Ingenieros con ingenio   coaching para ingenierosIngenieros con ingenio   coaching para ingenieros
Ingenieros con ingenio coaching para ingenieros
Aaron Perez Becerril
 
Firebox NAPAC Paper on Wind Energy
Firebox NAPAC Paper on Wind EnergyFirebox NAPAC Paper on Wind Energy
Firebox NAPAC Paper on Wind EnergyMike Schiller
 

Viewers also liked (17)

Romantizam
RomantizamRomantizam
Romantizam
 
Solución pc2
Solución pc2Solución pc2
Solución pc2
 
Encimera AEG HC412001GB
Encimera AEG HC412001GBEncimera AEG HC412001GB
Encimera AEG HC412001GB
 
Derrick Washington Resume 2016 - Copy
Derrick Washington Resume 2016 - CopyDerrick Washington Resume 2016 - Copy
Derrick Washington Resume 2016 - Copy
 
Universidad técnica de ambato
Universidad técnica de ambatoUniversidad técnica de ambato
Universidad técnica de ambato
 
Evolution of the infographic: Then, now, and future-now.
Evolution of the infographic: Then, now, and future-now. Evolution of the infographic: Then, now, and future-now.
Evolution of the infographic: Then, now, and future-now.
 
Estudos intenerantes
Estudos intenerantesEstudos intenerantes
Estudos intenerantes
 
Inflammatory Overgrowths
Inflammatory OvergrowthsInflammatory Overgrowths
Inflammatory Overgrowths
 
Solar Power Satellites
Solar Power SatellitesSolar Power Satellites
Solar Power Satellites
 
05 junit
05 junit05 junit
05 junit
 
Ganesh Kumar K_CV
Ganesh Kumar K_CVGanesh Kumar K_CV
Ganesh Kumar K_CV
 
Servicing 'Core and Chore': A framework for understanding a Modern IT Working...
Servicing 'Core and Chore': A framework for understanding a Modern IT Working...Servicing 'Core and Chore': A framework for understanding a Modern IT Working...
Servicing 'Core and Chore': A framework for understanding a Modern IT Working...
 
The role of the central IT Services organisation in a Web 2.0 world - paper
The role of the central IT Services organisation in a Web 2.0 world - paperThe role of the central IT Services organisation in a Web 2.0 world - paper
The role of the central IT Services organisation in a Web 2.0 world - paper
 
Ostern
Ostern Ostern
Ostern
 
1 aula 6 aducao
1 aula 6   aducao1 aula 6   aducao
1 aula 6 aducao
 
Ingenieros con ingenio coaching para ingenieros
Ingenieros con ingenio   coaching para ingenierosIngenieros con ingenio   coaching para ingenieros
Ingenieros con ingenio coaching para ingenieros
 
Firebox NAPAC Paper on Wind Energy
Firebox NAPAC Paper on Wind EnergyFirebox NAPAC Paper on Wind Energy
Firebox NAPAC Paper on Wind Energy
 

Similar to 04 threads-pbl-2-slots

OS Module-2.pptx
OS Module-2.pptxOS Module-2.pptx
OS Module-2.pptx
bleh23
 
[iOS] Multiple Background Threads
[iOS] Multiple Background Threads[iOS] Multiple Background Threads
[iOS] Multiple Background Threads
Nikmesoft Ltd
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Aravindharamanan S
 
Sucet os module_2_notes
Sucet os module_2_notesSucet os module_2_notes
Sucet os module_2_notes
SRINIVASUNIVERSITYEN
 
slides8 SharedMemory.ppt
slides8 SharedMemory.pptslides8 SharedMemory.ppt
slides8 SharedMemory.ppt
aminnezarat
 
Techno-Fest-15nov16
Techno-Fest-15nov16Techno-Fest-15nov16
Techno-Fest-15nov16
Satish Navkar
 
Mobile Application Development- Configuration and Android Installation
Mobile Application Development- Configuration and Android InstallationMobile Application Development- Configuration and Android Installation
Mobile Application Development- Configuration and Android Installation
Chandrakant Divate
 
multithreading
multithreadingmultithreading
multithreading
Rajkattamuri
 
Operating Systems
Operating Systems Operating Systems
Operating Systems
Ziyauddin Shaik
 
Chapter 02
Chapter 02Chapter 02
Chapter 02 Google
 
Os notes
Os notesOs notes
Os notes
LakshmiSarvani6
 
CS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMSCS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMS
Kathirvel Ayyaswamy
 
Crash dump analysis - experience sharing
Crash dump analysis - experience sharingCrash dump analysis - experience sharing
Crash dump analysis - experience sharingJames Hsieh
 
Multithreading
MultithreadingMultithreading
Multithreading
F K
 
Java
JavaJava
Operating System / System Operasi
Operating System / System Operasi                   Operating System / System Operasi
Operating System / System Operasi
seolangit4
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
Mohammed625
 

Similar to 04 threads-pbl-2-slots (20)

OS Module-2.pptx
OS Module-2.pptxOS Module-2.pptx
OS Module-2.pptx
 
Java multi thread programming on cmp system
Java multi thread programming on cmp systemJava multi thread programming on cmp system
Java multi thread programming on cmp system
 
[iOS] Multiple Background Threads
[iOS] Multiple Background Threads[iOS] Multiple Background Threads
[iOS] Multiple Background Threads
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01
 
Sucet os module_2_notes
Sucet os module_2_notesSucet os module_2_notes
Sucet os module_2_notes
 
slides8 SharedMemory.ppt
slides8 SharedMemory.pptslides8 SharedMemory.ppt
slides8 SharedMemory.ppt
 
Techno-Fest-15nov16
Techno-Fest-15nov16Techno-Fest-15nov16
Techno-Fest-15nov16
 
Mobile Application Development- Configuration and Android Installation
Mobile Application Development- Configuration and Android InstallationMobile Application Development- Configuration and Android Installation
Mobile Application Development- Configuration and Android Installation
 
multithreading
multithreadingmultithreading
multithreading
 
Operating Systems
Operating Systems Operating Systems
Operating Systems
 
OS_module2. .pptx
OS_module2.                          .pptxOS_module2.                          .pptx
OS_module2. .pptx
 
Chapter 02
Chapter 02Chapter 02
Chapter 02
 
Chapter 02
Chapter 02Chapter 02
Chapter 02
 
Os notes
Os notesOs notes
Os notes
 
CS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMSCS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMS
 
Crash dump analysis - experience sharing
Crash dump analysis - experience sharingCrash dump analysis - experience sharing
Crash dump analysis - experience sharing
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java
JavaJava
Java
 
Operating System / System Operasi
Operating System / System Operasi                   Operating System / System Operasi
Operating System / System Operasi
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 

More from mha4

Mule chapter2
Mule chapter2Mule chapter2
Mule chapter2
mha4
 
Mule Introduction
Mule IntroductionMule Introduction
Mule Introduction
mha4
 
Introduce Mule
Introduce MuleIntroduce Mule
Introduce Mule
mha4
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object java
mha4
 
OOP for java
OOP for javaOOP for java
OOP for java
mha4
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 

More from mha4 (8)

Mule chapter2
Mule chapter2Mule chapter2
Mule chapter2
 
Mule Introduction
Mule IntroductionMule Introduction
Mule Introduction
 
Introduce Mule
Introduce MuleIntroduce Mule
Introduce Mule
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object java
 
OOP for java
OOP for javaOOP for java
OOP for java
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 

Recently uploaded

Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.pptPROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
bhadouriyakaku
 
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
obonagu
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
yokeleetan1
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
Mukeshwaran Balu
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 

Recently uploaded (20)

Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.pptPROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
 
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 

04 threads-pbl-2-slots

  • 1. Lecture 04 Chapter 7: Threads (35 slides- 2 slots)
  • 2. Why should you study this chapter?  This chapter will help you developing a program in which some tasks executing concurrently.  Nowadays, in one program, some tasks execute concurrently. You usually saw them in a web page including texts, sounds, images, games, … changing concurrently.  Nowadays, operating systems (OS) support many programs running concurrently.  Open the Task Manager of Windows OS (Ctrl Alt Delete) to see how many programs are running in your computer. 2
  • 3. Review Previous lecture:  Introduction to OO Paradigm  Benefits of OO Implementation  Hints for class design  Declaring/ Using classes/ abstract classes/ Interfaces/ Anonymous classes/ Enum types 3
  • 4. Objectives  Definitions: Process, thread.  Multi-Processing System and Multi-Threading Program.  What are threads.  Thread Fundamentals in Java  Monitors, Waiting and Notifying Your homework: Workshop 3 (with report): The producer-consumer problem and the philosophers problem. Workshop 4 (with report): Deadlock application. Refer to the source code in the page 236 of the book Complete Java 2 Certification. Explain why the application causes deadlock. Assessment: the next class. 4
  • 5. 1- Definitions  Program-chương trình: An executable file (data + code) stored in secondary memory(disk).  Process- tiến trình: A program in running. It’s data and code are loaded to RAM in a contiguous memory block.  Thread- luồng: is a smallest unit code (function/method) in an application that performs a special job. An application can contain some threads. A thread can be called as lightweight process. Data Code Thread 1 Thread 2 Thread 3 5
  • 6. 7.1- Processes and Multi Processing System  A process has a self-contained execution environment. A process generally has a complete, private set of basic run- time resources; in particular, each process has its own memory space.  Multi Processing/ Multi Tasking System: Almost of operating systems allows many processes executing concurrently.  Open the Task Manager of Windows OS ( Ctrl+Alt+Del) to see current processes in your computer.  Applications tag contains processes which you start them.  Processes tag contains processes which automatically run immediately after the startup of OS. 6
  • 7. How can OS manage concurrent processes Memory App1 Code Data App2 Code Data App3 Code Data App Code Addr Duration (mili sec) CP U … App 1 10320 15 1 App 2 40154 17 2 App 3 80166 22 1 … … … … … … … … Process Table maintains information of processes. How does OS manage executions of processes? Time-slicing mechanism. Each process is allocated resources ( CPU, …) for executing in a time-slot (such as 30 milliseconds). When the time duration expires, this process will pause to yield resources to the next process which will be chosen by the scheduler of OS.7
  • 8. 7.2- Threads and Multi-Threading  Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.  Threads exist within a process — every process has at least one thread (main thread). Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.  Multithreaded execution is an essential feature of the Java platform. Threads in a program are managed by the JVM. 8
  • 9. How can JVM manage threads Memory of a multi-thread process App Data Code of thread1 Code of thread2 Code of thread3  Thread is a smallest unit code in an application that performs a special job.  A program can have several threads they can be executed concurrently. Thread Code Addr Duratio n (mili sec) CPU State Thread 1 10320 15 1 ready Thread 2 40154 17 2 ready Thread 3 80166 22 1 sleep Thread Table maintains information of threads Time-slicing mechanism is used to schedule thread executions also. 9
  • 11. Race Conditions Application Data 1 (shared data) Data 2 Data 3 Thread 1 Thread 2 Thread3 Thread 4 A race occur s Need Synchronizatio n Suppose that Thread2 and Thread4 concurrently execute. Time Thread 2 Thread4 1 Data1=10 … 2 …. … 3 …. Data1= 100 4 …. … 5 … … 6 Y= Data1; … 7 … Y= ? 11
  • 12. 7.3- Thread Fundamentals in Java  Threading supports in Java:  The java.lang.Thread class  The java.lang.Object class  The Java language and JVM ( Java Virtual Machine)  How to create a thread in Java? (1) Create a subclass of the java.lang.Thread class and override the method run() (2) Create a class implementing the Runnable interface and override the run() method. 12
  • 13. Threa d Code Addr State … main 8000 run … t 10320 run Create a subclass of the Thread class Thread table Every process has at least one thread (main thread). ? The start() method is implemented in the Thread class. This method calls the method run(). This process has 2 threads running concurrently. At a time, order of their execution is decided by the scheduler. 13
  • 14. Class implements the Runnable interface Threa d Code Addr State … main 8000 run … t 10320 run 14
  • 15. The java.lang.Thread class Constructor Thread() Thread(Runnable target) Thread(Runnable target, String name) Thread(String name) Thread(ThreadGroup group, Runnable target) Thread(ThreadGroup group, Runnable target, String name) Thread(ThreadGroup group, Runnable target, String name, long stackSize) Thread(ThreadGroup group, String name) Declaration public class Thread extends Object implements Runnable Common Methods start() join () sleep (milisec) yield() notify() notifyAll() wait() Properties id name state threadGroup daemon priority set/get-is 15
  • 16. Using some methods of the Thread class 16
  • 17. Thread States Running BlockedSleeping Suspende d Ready Monitor States (JVM) yield() start() (Scheduler) sleep(milisec) Time expired or interrupted Blocking method (IO) Blocking condition changes or interrupt wait() notify() Ready: As soon as it is created , it can enter the running state when JVM’s processor is assigned to it. Running: It get full attention of JVM’s processor which executes the thread’s run() method Dead: When the run() method terminates. Interrupt: A signal is sent to CPU from IO device just after an IO operation has terminated.Only ready threads will be chosen by the JVM scheduler at a time. 17
  • 18. Non-race Demonstration This program contains 2 threads: - The first thread that will print out the system time for every second. - The second will print out the sum of two random integers for every half of a second. 18
  • 20. 7.4- Monitors, Waiting and Notifying  Some threads can access common resources concurrently. We must synchronize accessing common resources  Every object has a lock  Lock: an extra variable is added by the compiler for monitoring the state of common resource. Before a thread accesses the common resource, the lock is tested.  After a thread has the lock (it is permitted to access the common resource), it can access common resource. When it did, it needs notifying to others thread ( wait-notify mechanism). Running Seeking Lock waiting Ready Scheduler wait()notify(), notifyAll(), time out, or interrupt Enter synchronized code Lock obtained 20
  • 21. Monitors, Waiting and Notifying…  Two ways to mark code as synchronize  Synchronize an entire method: Let the synchronized modifier in the method’s declaration. synchronized Type Method(args){ <code> }  Synchronize some method of an object Type Method ( args){ …… synchronized ( object_var){ object_var.method1(args); object_var.method2(args); } } A class contains synchronized code is called monitor. Monitor: A technique to encapsulate common resources to a class. When a thread wants to access common resources, it must call a public synchronized method. As a result, common resources are accessed in successive manner.21
  • 22. Demo:The Producer-Consumer Problem - Producer makes a product then puts it to a store. - Consumer buys a product from a store. - Selling Procedure: First In First Out Attention!: Store is common resource of 2 threads: producer and consumer.  Store is a monitor and it’s activities needs synchronization Synchronizing: * After a thread accessed common resource, it should sleep a moment or it must notify to the next thread ( or all thread) in the thread-pool to awake and execute. * Use the synchronized keyword to declare a method that will access common resource. Producer Consume r produc t produc t Put to the tail Get from the head Store 22
  • 23. The Producer-Consumer Problem /* synchronized */ No synchronization A product is simulated as a number. 23
  • 26. The Producer-Consumer Problem Synchronization is not used Synchronization is used: 26
  • 27. 7.5- Deadlock What is deadlock? Deadlock describes a situation where two or more threads are blocked forever, waiting for each other  All threads in a group halt. When does deadlock occur? There exists a circular wait the lock that is held by other thread. Nothing can ensure that DEADLOCK do not occur. 27
  • 29. The Philosophers Problem Wait-Notify Mechanism, a way helps preventing deadlocks 3 classes Deadlock! 29
  • 30. The Philosophers Problem Threa d Code Addr Duration (mili sec) CP U State Thread 1 10320 15 1 Suspended Ready Thread 2 40154 17 2 Suspended Thread 3 80166 22 1 Suspended … … … … …. Thread pool 30
  • 33. Summary Concepts were introduced:  Definitions: Program, Process, Thread  Multi-processing system  Multi-threading programming in Java  Thread Fundamentals in Java  Synchronizing access to common resource.  Monitoring thread states: Wait-notify mechanism.  If you want some tasks executing concurrently, multi-threading is a solution. 33
  • 34. Exercises Workshop 3 (with report): The producer-consumer problem and the philosophers problem. Workshop 4 (with report): Deadlock application. Refer to the source code in the page 236 of the book Complete Java 2 Certification. Explain why the application causes deadlock. 34

Editor's Notes

  1. Synchronize –đồng(cùng) bộ(bước chân). Bản chất của sự đồng bộ là chờ nhau. Trong tin học, đồng bộ một nhóm tac vụ là cưỡng bức các tác vụ này phải thực thi tuần tự (không cho phép thực thi đồng thời). Giao tiếp đồng bộ là giao tiếp chỉ có một người nói tại một thời điểm (khi phỏng vấn, giao tiếp hình thức). Giao tiếp không đồng bộ là giao tiếp ở đó mọi người đều có thể nói đồng thời (khi cãi lộn).
  2. join(): kết hợp  Luồng hiện hành sẽ chạy cho đến khi luồng kết thúc yield(): nhường  Luồng hiện hành chủ động tạm ngưng, nhường CPU cho luồng khác notify(): Cảnh báo Luồng hiện hành giao tiếp với JVM, yêu cầu JVM cho luồng ở đầu hàng đợi ready để khi lập lịch, luồng này sẽ được thực thi. Hành vi notify() thường được dùng ngay sau hành vi wait()  JVM modifies thread table notifyAll(): cảnh báo tất cả Luồng hiện hành yêu cầu JVM cho tất cả các luồng trong hàng đJVM modifies thread table