AOOP Chapter1 Threads
AOOP Chapter1 Threads
Chapter 1 - Threads
UFAZ / 2018-2019
Cecilia ZANNI-MERK
Agenda
● Introducing Threads
● Synchronization
● Scheduling and Priority
● Thread Groups
2
Notion of process
3
Notion of process
4
Notion of process
● running
● ready to run (but no free processor to run it)
● blocked (because of lack of resources)
5
Notion of process
6
Threads
7
Threads
8
Inheriting from the Thread class
9
Example
10
Overview of the Thread class
Constants
Constructors
● Thread() ;
● Thread(Runnable target, String name)
● . . .
11
Overview of the Thread class
Methods
Methods
13
Overview of the Thread class
Methods
14
Example
15
Implementing the Runnable the interface
16
Example
17
The join() method
18
Example
19
Threads management with synchronized
We can synchronize
21
Threads management with synchronized
22
Threads management with synchronized
Remarks:
23
Example with no synchronization
24
Example with no synchronization
25
Example with no synchronization
26
Example with no synchronization
Execution
27
Example with synchronization
28
Example with synchronization
Execution
29
wait() and notify()
30
wait() and notify()
More in detail:
31
wait() and notify()
32
Example
33
Example
34
First version: Warehouse takes care of synchronisation
35
First version: Warehouse takes care of synchronisation
36
First version: Warehouse takes care of synchronisation
37
2nd version: Producer and Consumer manage synch.
38
2nd version: Producer and Consumer manage synch.
39
2nd version: Producer and Consumer manage synch.
40
2nd version: Producer and Consumer manage synch.
41
Final remarks
42
Supervised exercises
1. Download and test all the examples presented during the lecture
a. Slide 19. Execute several times the example and compare the results
of those executions. What happens if you change the number of
milliseconds in the sleep method? Explain and justify
b. Do the same for the examples in slides 29 and 37
c. Compare the two versions of the same problem in slides 37 and 41.
Discuss the advantages and disadvantages of both approaches
2. Download and analyse the source code in slide 43 (classes
MyObject.java, MyThread.java, Deadlock.java)
a. Explain where there are mistakes and propose solutions.
b. Study the notions of starvation, livelock and deadlock and how to
prevent them
43
Supervised exercises
44
Mini-Project
45