SlideShare uma empresa Scribd logo
1 de 22
Concurrency
( Part 1)
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
Concepts introduced in the course OOP using Java:
Object = properties + methods
Benefits of OO Implementation: encapsulation,
inheritance, polymorphism
Encapsulation is implemented by modifiers
Inheritance: Subclass inherits declaration of base class
(Java is a single inheritance OOP language, the class
Object is the ultimate Java class
 Polymorphism in Java is implemented by overloading
and overriding methods
3
Review
Class: A template (blueprint) for a group of
similar instances
Interface: the core of some classes
Abstract class is a class containing abstract
methods (some methods are prototyped only)
Anonymous class: A concrete class developed
from an abstract class or an interface but it is not
named:
Nested class: a class which is declared in the
declaration of the enclosing class
Enum type: Declaration of some constants
4
Review
 Class Declaration:
[public] class ClassName [extends BaseClass] [implements Interface] {
[modifiers] DataType field1 [ = initialValue];
[modifier] ClassName (params) { // constructor
<code>
}
[modifier] methodName(params) { // method
<code>
}
}
 Creating objects: ClassName obj = new ClassName(params)
 Accessing an object: obj.field or obj.methodeName(args)
5
Objectives
Multi-Processing System
Threads and Multi-Threading Program
Thread Fundamentals in Java
6
1- Processes and
Multi-Processing System
Program: An executable file
(data + code) stored in
secondary memory(disk).
Process: A program in running.
It’s data and code are loaded to
RAM in a contiguous memory
block.
Multi-Processing System: An
operating system allows some
processes running concurrently
7
Data
Code
Data
Code
Data
Code
Data
Code
P1
P2
P3
P4
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.
8
Processes and Multi Processing System…
9
CPU 2 cores  1 core runs 33 (66/2) processes
 Pseudo -parallelism
Processes and Multi Processing System…
10
How OS manages processes based on one
CPU?
 Time-sharing mechanism: OS allows each
process running in a time slot (time slice,
quantum, about 50 to 70 ms). When this duration
expires, another process will be chosen to run 
The scheduler (a component of OS, trình lập lịch)
will choose the current process.
t
p1
p2
p3
Processes and Multi Processing System…
How can OS manage concurrent processes?
Memory
P1
Code
Data
P2
Code
Data
P3
Code
Data
App Code
Addr
Duration
(mili sec)
CPU …
P1 30320 50 1
P2 20154 60 2
P3 10166 70 1
… … … …
… … … …
Process Table maintains information of processes.
Time-slicing mechanism. Each process is allocated resources
( CPU, …) for executing in a time-slot (such as 50
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.11
2- Threads and Multi-Threading
Thread, is sometimes called lightweight processes, is
a running code unit.
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.
Both processes and threads are provided an
execution environment, but creating a new thread
requires fewer resources than creating a new process.
Multithreaded execution is an essential feature of the
Java platform. Threads in a program are managed by
the JVM. Scheduler in JVM will choose a current
thread.
12
Threads and Multi-Threading …
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
Duration
(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.
13
Threads and Multi-Threading …
Processes VS Threads
Memory
App1
Data
Code
App2
Data
Code
App3
Data
Code
Memory
App1
data
Code
Thread1
Thread2
Thread3
14
Protection mechanism in OS
does not allow this process
accessing addresses in others
Threads in a process can
access common data of this
process
Threads and Multi-Threading …
Race Conditions
Application
Data 1 (shared data)
Data 2
Data 3
Thread 1
Thread 2
Thread3
Thread 4
A race
occurs
Need
Synchronization
Suppose that Thread2 and Thread4 concurrently
execute.
Time Thread 2 Thread4
1 Data1=10 …
2 …. …
3 …. Data1= 100
4 …. …
5 … …
6 Y= 2*Data1; …
7 …
Y=?
15
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.
16
Thread 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.17
Class implements the Runnable interface
Thread Code Addr State …
main 8000 run …
t 10320 run
18
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
19
Using some methods of the Thread class
20
Thread States
Monitor
States
(JVM)
yield()
start()
(Scheduler)
sleep(millisecond)
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 one of ready threads will be
chosen by the JVM scheduler at a time.
21
Summary
Concepts were introduced:
Definitions: Program, Process, Thread
Multi-processing system
Multi-threading programming in Java
Thread Fundamentals in Java
Thread states
22

Mais conteúdo relacionado

Mais procurados

Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in javaAbhra Basak
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slotsmha4
 
Multithreading
MultithreadingMultithreading
MultithreadingA B Shinde
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 
Multithreading
MultithreadingMultithreading
Multithreadingsagsharma
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
Correct and efficient synchronization of java thread
Correct and efficient synchronization of java threadCorrect and efficient synchronization of java thread
Correct and efficient synchronization of java threadoutofmemoryerror
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Multi threading
Multi threadingMulti threading
Multi threadinggndu
 

Mais procurados (19)

Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in java
 
Multithread
MultithreadMultithread
Multithread
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
Multithreading
MultithreadingMultithreading
Multithreading
 
java threads
java threadsjava threads
java threads
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Correct and efficient synchronization of java thread
Correct and efficient synchronization of java threadCorrect and efficient synchronization of java thread
Correct and efficient synchronization of java thread
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Multi threading
Multi threadingMulti threading
Multi threading
 

Semelhante a Slot02 concurrency1

Semelhante a Slot02 concurrency1 (20)

04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
 
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
 
Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2
 
Operating System 4
Operating System 4Operating System 4
Operating System 4
 
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptxWEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
 
Java
JavaJava
Java
 
multithreading
multithreadingmultithreading
multithreading
 
OS Module-2.pptx
OS Module-2.pptxOS Module-2.pptx
OS Module-2.pptx
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
Java
JavaJava
Java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Basic java part_ii
Basic java part_iiBasic java part_ii
Basic java part_ii
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Operating Systems - "Chapter 4: Multithreaded Programming"
Operating Systems - "Chapter 4:  Multithreaded Programming"Operating Systems - "Chapter 4:  Multithreaded Programming"
Operating Systems - "Chapter 4: Multithreaded Programming"
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Threads presentation
Threads presentationThreads presentation
Threads presentation
 
Threads
ThreadsThreads
Threads
 
Os
OsOs
Os
 

Último

Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 

Último (20)

Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 

Slot02 concurrency1

  • 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 Concepts introduced in the course OOP using Java: Object = properties + methods Benefits of OO Implementation: encapsulation, inheritance, polymorphism Encapsulation is implemented by modifiers Inheritance: Subclass inherits declaration of base class (Java is a single inheritance OOP language, the class Object is the ultimate Java class  Polymorphism in Java is implemented by overloading and overriding methods 3
  • 4. Review Class: A template (blueprint) for a group of similar instances Interface: the core of some classes Abstract class is a class containing abstract methods (some methods are prototyped only) Anonymous class: A concrete class developed from an abstract class or an interface but it is not named: Nested class: a class which is declared in the declaration of the enclosing class Enum type: Declaration of some constants 4
  • 5. Review  Class Declaration: [public] class ClassName [extends BaseClass] [implements Interface] { [modifiers] DataType field1 [ = initialValue]; [modifier] ClassName (params) { // constructor <code> } [modifier] methodName(params) { // method <code> } }  Creating objects: ClassName obj = new ClassName(params)  Accessing an object: obj.field or obj.methodeName(args) 5
  • 6. Objectives Multi-Processing System Threads and Multi-Threading Program Thread Fundamentals in Java 6
  • 7. 1- Processes and Multi-Processing System Program: An executable file (data + code) stored in secondary memory(disk). Process: A program in running. It’s data and code are loaded to RAM in a contiguous memory block. Multi-Processing System: An operating system allows some processes running concurrently 7 Data Code Data Code Data Code Data Code P1 P2 P3 P4
  • 8. 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. 8
  • 9. Processes and Multi Processing System… 9 CPU 2 cores  1 core runs 33 (66/2) processes  Pseudo -parallelism
  • 10. Processes and Multi Processing System… 10 How OS manages processes based on one CPU?  Time-sharing mechanism: OS allows each process running in a time slot (time slice, quantum, about 50 to 70 ms). When this duration expires, another process will be chosen to run  The scheduler (a component of OS, trình lập lịch) will choose the current process. t p1 p2 p3
  • 11. Processes and Multi Processing System… How can OS manage concurrent processes? Memory P1 Code Data P2 Code Data P3 Code Data App Code Addr Duration (mili sec) CPU … P1 30320 50 1 P2 20154 60 2 P3 10166 70 1 … … … … … … … … Process Table maintains information of processes. Time-slicing mechanism. Each process is allocated resources ( CPU, …) for executing in a time-slot (such as 50 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.11
  • 12. 2- Threads and Multi-Threading Thread, is sometimes called lightweight processes, is a running code unit. 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. Both processes and threads are provided an execution environment, but creating a new thread requires fewer resources than creating a new process. Multithreaded execution is an essential feature of the Java platform. Threads in a program are managed by the JVM. Scheduler in JVM will choose a current thread. 12
  • 13. Threads and Multi-Threading … 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 Duration (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. 13
  • 14. Threads and Multi-Threading … Processes VS Threads Memory App1 Data Code App2 Data Code App3 Data Code Memory App1 data Code Thread1 Thread2 Thread3 14 Protection mechanism in OS does not allow this process accessing addresses in others Threads in a process can access common data of this process
  • 15. Threads and Multi-Threading … Race Conditions Application Data 1 (shared data) Data 2 Data 3 Thread 1 Thread 2 Thread3 Thread 4 A race occurs Need Synchronization Suppose that Thread2 and Thread4 concurrently execute. Time Thread 2 Thread4 1 Data1=10 … 2 …. … 3 …. Data1= 100 4 …. … 5 … … 6 Y= 2*Data1; … 7 … Y=? 15
  • 16. 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. 16
  • 17. Thread 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.17
  • 18. Class implements the Runnable interface Thread Code Addr State … main 8000 run … t 10320 run 18
  • 19. 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 19
  • 20. Using some methods of the Thread class 20
  • 21. Thread States Monitor States (JVM) yield() start() (Scheduler) sleep(millisecond) 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 one of ready threads will be chosen by the JVM scheduler at a time. 21
  • 22. Summary Concepts were introduced: Definitions: Program, Process, Thread Multi-processing system Multi-threading programming in Java Thread Fundamentals in Java Thread states 22

Notas do Editor

  1. Synchronize –đồng(cùng) bộ(bước chân). Bản chất của sự đồng bộ là sự chờ nhau. Trong tin học, đồng bộ một nhóm tác 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 chuyển trạng thái thành 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 đợi được chuyển trạng thái sang ready