SlideShare a Scribd company logo
CONCURRENT PROGRAMMING
THREAD’S BASICS
PROGRAMMAZIONE CONCORRENTE E DISTR.
Università degli Studi di Padova
Dipartimento di Matematica
Corso di Laurea in Informatica, A.A. 2015 – 2016
rcardin@math.unipd.it
Programmazione concorrente e distribuita
SUMMARY
 Introduction
 Thread basics
 Thread properties
 Thread states
 Thread interruption
 Sequence diagrams
2Riccardo Cardin
Programmazione concorrente e distribuita
INTRODUCTION
 Multitasking
 The ability to have more than a program working at
what seems like the same time
 The unity of this type of programming is a process
 A process has its own variables
 Communication between process is accomplished using
messages sent over a common channel (i.e. a socket)
 Very hard to accomplish and no so performant
 Types
 Cooperative: CPU control is left to the processes
 Time-sliced: the OS (scheduler) assigns a time slice to each
process
3Riccardo Cardin
Programmazione concorrente e distribuita
INTRODUCTION
 Multithread
 A programming model that allows multiple threads to
exists within the same context of a single process
 Every process will appear to do multiple tasks
 Threads share the same data and variables
 Every process as a main thread
 This thread can create other threads, called secondary
 Every thread as a priority order (1 .. 10)
 Types
 Cooperative
 Time-sliced: thread scheduling is left to the main thread, that
uses OS utilities
4Riccardo Cardin
Programmazione concorrente e distribuita
INTRODUCTION
5Riccardo Cardin
Programmazione concorrente e distribuita
INTRODUCTION
6Riccardo Cardin
Process
Memory
Thread 1
Task Task
Thread 2
Task
Thread 3
Task
Threads
share the
same
memory
chunks
Every thread
could be reused
to execute
different tasksThreads are
lighter than
processes, even
so their creation
is still time-
consuming
Each process
can execute
many threads
Threads are a
mechanism provided
by the OS
Programmazione concorrente e distribuita
DEFINITION
 Multithread programming
 A programming model that allows multiple threads to
exists within the same context of a single process
 Responsiveness
 Faster execution
 Lower resource consumption
 Parallelization
 Java has built-in support for concurrent programming
7Riccardo Cardin
A thread is the smallest sequence of programmed instructions that can
be managed independently. Multiple thread can exist within the same
process, executing concurrently and share resources such as memory.
- Wikipedia
Programmazione concorrente e distribuita
THREAD BASICS
 Threads in Java are the primitives that actually
execute tasks
 Runnable interface describes a task you want to
run, usually concurrently with others
 The code of the run method will be executed in a thread
 Tasks are short lived, so you don’t waste the time to start a
thread
8Riccardo Cardin
public interface Runnable {
void run();
}
Runnable task = () -> {
int i = 0;
while (i < 1000) i++;
}
new Thread(task).start(); // A thread running a task
Programmazione concorrente e distribuita
THREAD BASICS
 You should decouple the task that is to be run in
parallel from the mechanism of running it
 You can also define a subclass of Thread, but this
approach is no longer recommended
 If you have many task is to expensive create a single thread
for each one
 Do not call the run method on Thread or Runnable
instances
 The task is merely executed in the same thread
9Riccardo Cardin
class MyThread extends Thread {
public void run() {
// task code, don’t do this!!!
}
}
Programmazione concorrente e distribuita
THREAD BASICS
10Riccardo Cardin
Programmazione concorrente e distribuita
THREAD BASICS
 The main method executes in the main thread
 From the main thread they can be executed other
thread, called secondary
 They execute in pararrel wrt the main thread
 Threads can be of two type
 User threads
 JVM stops when there are no more user thread executing
 Deamon threads
 A deamon stops when its user thread stops
11Riccardo Cardin
public class Example {
public static void main(String[] args) {
// This code runs inside the main thread
}
}
Programmazione concorrente e distribuita
THREAD PROPERTIES
 Thread priorities
 Use setPriority method to give a thread a priority
 MIN_PRIORITY = 1 and MAX_PRIORITY = 10
 Don’t use priorities, they are too highly system-dependent
 Deamon threads
 Use setDeamon method
 Its only role is to serve other threads
 When only deamon threads remain, the JVM exits
 Handlers for uncaught exceptions
 The run method cannot throw any checked ex.
 Install an UncaughtExceptionHandler to manage ex.
12Riccardo Cardin
Programmazione concorrente e distribuita
THREAD STATES
 6 thread states
 New
 Runnable
 Blocked
 Waiting
 Time waiting
 Terminated
 Use getState
method
 Thread.State
13
No resources
associated
Runnable ≠
Running
Programmazione concorrente e distribuita
THREAD STATES
 New threads
 Just created with the new operator. Not yet running
 Runnable threads
 Once the start method is invoked.
 Resource creation, scheduling
 run method is invoked
 It may or not actually be running
 DO NOT CALL RUN METHOD DIRECTLY!
14Riccardo Cardin
public static void main(String[] args) {
// Not concurrent, but sequential
new MyThread().run();
for (int i = 0; i < 200; i++)
System.out.println("Cycle - " + i);
}
Programmazione concorrente e distribuita
THREAD STATES
 Blocked and Waiting threads
 Temporarily inactive
 A thread becomes blocked when it tries to acquire an
intrinsic object lock
 When a thread waits for another thread to notify of a
condition, it enters the waiting state
 The calling of a timeout parameters causes the thread to
enter the timed waiting (Thread.sleep)
 A thread waits for another thread to finish, calling the join
method on it
 Terminated threads
 It is not possible to reborn a thread in this state
15Riccardo Cardin
Programmazione concorrente e distribuita
THREADS INTERRUPTION
 A thread terminates when it’s run method:
 Returns by executing a return statement
 After executing the last statement in method body
 If an unhandled exception occurs
 It is possible to send an interruption request
 Use the interrupt method
 Thread states becomes interrupted, but thread is not
interrupted by the JVM
 Thread should check whether it has been interrupted
16Riccardo Cardin
while (!Thread.currentThread().isInterrupted() && more work to do) {
// do more work
}
Programmazione concorrente e distribuita
THREADS INTERRUPTION
 Waiting for another thread to finish
 Use join() or join(long millis)
 An instance of the joining thread must be available
 Passing a time interval to the method has the effect to limit
the waiting period to millis milliseconds
17Riccardo Cardin
Thread thread = new Thread(() -> {
// Do some heavy work
});
thread.start();
try {
// Waiting for at max 1 second the termination of thread
thread.join(1000L);
} catch(InterruptedException e) {
// thread was interrupted during sleep
} finally {
// cleanup, if required
}
Programmazione concorrente e distribuita
THREADS INTERRUPTION
 Implementing collaborative preemption
 Thread.yield() notifies the system that the current
thread is willing to "give up the CPU" for a while.
 Thread scheduler will select a different thread to run
 If no other thread is present, the statement has no effect
 When to use yield()? Practically NEVER
 Use Thread.sleep() (requires some self-computation)
 Use synchronization mechanisms if waiting for a process or
a resource
18Riccardo Cardin
while ( /* more work to do */ ) {
// do more work
Thread.yield();
}
Programmazione concorrente e distribuita
THREADS INTERRUPTION
 Interrupting a thread simply grabs its attention
 Use Thread.sleep(long time) to suspend
temporarily the thread
 If the interrupted thread was sleeping or waiting for
something, an InterruptedException is thrown
 ...and the thread status is cleared!
19Riccardo Cardin
try {
while ( /* more work to do */ ) {
// do more work
Thread.sleep(delay);
}
} catch(InterruptedException e) {
// thread was interrupted during sleep
} finally {
// cleanup, if required
}
Programmazione concorrente e distribuita
THREADS INTERRUPTION
20Riccardo Cardin
Programmazione concorrente e distribuita
SEQUENCE DIAGRAMS
 How can we reason about thread visually?
 UML gives use sequence diagrams
21Riccardo Cardin
Partecipant
Timepassing
Life line
Programmazione concorrente e distribuita
SEQUENCE DIAGRAMS
22Riccardo Cardin
A sequence diagram describes the cooperation between a group of
objects that have to interact with each other to fulfill an objective
Definition
Message
Find message
Internal call
Return
Object
creation
Programmazione concorrente e distribuita
EXAMPLES
23Riccardo Cardin
https://github.com/rcardin/pcd-snippets
Programmazione concorrente e distribuita
REFERENCES
 Chap. 14 «Multithreading», Core Java Volume I - Fundamentals, Cay
Horstmann, Gary Cornell, 2012, Prentice Hall
 Thread.yield
http://www.javamex.com/tutorials/threads/yield.shtml
 What are the main uses of yield(), and how does it differ from join()
and interrupt()?
http://stackoverflow.com/questions/6979796/what-are-the-main-
uses-of-yield-and-how-does-it-differ-from-join-and-interr
 Chap. 10 «Concurrent Programming», Core Java for the Impatient,
Cay Horstmann, 2015, Addison-Wesley
24Riccardo Cardin

More Related Content

What's hot

Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
Riccardo Cardin
 
Java session13
Java session13Java session13
Java session13
Niit Care
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
 
Spin Locks and Contention : The Art of Multiprocessor Programming : Notes
Spin Locks and Contention : The Art of Multiprocessor Programming : NotesSpin Locks and Contention : The Art of Multiprocessor Programming : Notes
Spin Locks and Contention : The Art of Multiprocessor Programming : Notes
Subhajit Sahu
 
CS844 U1 Individual Project
CS844 U1 Individual ProjectCS844 U1 Individual Project
CS844 U1 Individual Project
ThienSi Le
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Hoang Nguyen
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best Practices
IndicThreads
 
System Verilog Functional Coverage
System Verilog Functional CoverageSystem Verilog Functional Coverage
System Verilog Functional Coverage
rraimi
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
kim.mens
 
Designing Better API
Designing Better APIDesigning Better API
Designing Better API
Kaniska Mandal
 
Introduction to-vhdl
Introduction to-vhdlIntroduction to-vhdl
Introduction to-vhdl
Neeraj Gupta
 
javarmi
javarmijavarmi
javarmi
Arjun Shanka
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
parveen837153
 
JavaFX In Practice
JavaFX In PracticeJavaFX In Practice
JavaFX In Practice
Richard Bair
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
Jonathan Simon
 

What's hot (16)

Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
 
Java session13
Java session13Java session13
Java session13
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 
Spin Locks and Contention : The Art of Multiprocessor Programming : Notes
Spin Locks and Contention : The Art of Multiprocessor Programming : NotesSpin Locks and Contention : The Art of Multiprocessor Programming : Notes
Spin Locks and Contention : The Art of Multiprocessor Programming : Notes
 
CS844 U1 Individual Project
CS844 U1 Individual ProjectCS844 U1 Individual Project
CS844 U1 Individual Project
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best Practices
 
System Verilog Functional Coverage
System Verilog Functional CoverageSystem Verilog Functional Coverage
System Verilog Functional Coverage
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
 
Designing Better API
Designing Better APIDesigning Better API
Designing Better API
 
Introduction to-vhdl
Introduction to-vhdlIntroduction to-vhdl
Introduction to-vhdl
 
javarmi
javarmijavarmi
javarmi
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
JavaFX In Practice
JavaFX In PracticeJavaFX In Practice
JavaFX In Practice
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
 

Viewers also liked

Design Pattern Strutturali
Design Pattern StrutturaliDesign Pattern Strutturali
Design Pattern Strutturali
Riccardo Cardin
 
Diagrammi di Sequenza
Diagrammi di SequenzaDiagrammi di Sequenza
Diagrammi di Sequenza
Riccardo Cardin
 
Introduzione ai Design Pattern
Introduzione ai Design PatternIntroduzione ai Design Pattern
Introduzione ai Design Pattern
Riccardo Cardin
 
Diagrammi delle Classi
Diagrammi delle ClassiDiagrammi delle Classi
Diagrammi delle Classi
Riccardo Cardin
 
Errori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiErrori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei Requisiti
Riccardo Cardin
 
Presto updates to 0.178
Presto updates to 0.178Presto updates to 0.178
Presto updates to 0.178
Kai Sasaki
 
Design pattern architetturali Model View Controller, MVP e MVVM
Design pattern architetturali   Model View Controller, MVP e MVVMDesign pattern architetturali   Model View Controller, MVP e MVVM
Design pattern architetturali Model View Controller, MVP e MVVM
Riccardo Cardin
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patterns
Riccardo Cardin
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics Programming
Riccardo Cardin
 
Design Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionDesign Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency Injection
Riccardo Cardin
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Scala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyScala - the good, the bad and the very ugly
Scala - the good, the bad and the very ugly
Bozhidar Bozhanov
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented Design
Riccardo Cardin
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
Enno Runne
 

Viewers also liked (14)

Design Pattern Strutturali
Design Pattern StrutturaliDesign Pattern Strutturali
Design Pattern Strutturali
 
Diagrammi di Sequenza
Diagrammi di SequenzaDiagrammi di Sequenza
Diagrammi di Sequenza
 
Introduzione ai Design Pattern
Introduzione ai Design PatternIntroduzione ai Design Pattern
Introduzione ai Design Pattern
 
Diagrammi delle Classi
Diagrammi delle ClassiDiagrammi delle Classi
Diagrammi delle Classi
 
Errori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiErrori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei Requisiti
 
Presto updates to 0.178
Presto updates to 0.178Presto updates to 0.178
Presto updates to 0.178
 
Design pattern architetturali Model View Controller, MVP e MVVM
Design pattern architetturali   Model View Controller, MVP e MVVMDesign pattern architetturali   Model View Controller, MVP e MVVM
Design pattern architetturali Model View Controller, MVP e MVVM
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patterns
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics Programming
 
Design Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionDesign Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency Injection
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Scala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyScala - the good, the bad and the very ugly
Scala - the good, the bad and the very ugly
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented Design
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 

Similar to Java - Concurrent programming - Thread's basics

Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
Rakesh Madugula
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
ajmalhamidi1380
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
happycocoman
 
Multithreading
MultithreadingMultithreading
Multithreading
Ravi Chythanya
 
Java Threads
Java ThreadsJava Threads
Java Threads
Hamid Ghorbani
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
Himanshu Rajput
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
Shipra Swati
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
kashyapneha2809
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
Elizabeth alexander
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
PreetiDixit22
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
Isuru Perera
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
Mohit Kumar
 
Multithreading
MultithreadingMultithreading
Multithreading
sagsharma
 

Similar to Java - Concurrent programming - Thread's basics (20)

Multithreading
MultithreadingMultithreading
Multithreading
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
 
Multithreading
MultithreadingMultithreading
Multithreading
 

More from Riccardo Cardin

Design Pattern Comportamentali
Design Pattern ComportamentaliDesign Pattern Comportamentali
Design Pattern Comportamentali
Riccardo Cardin
 
Design Pattern Creazionali
Design Pattern CreazionaliDesign Pattern Creazionali
Design Pattern Creazionali
Riccardo Cardin
 
Diagrammi di Attività
Diagrammi di AttivitàDiagrammi di Attività
Diagrammi di Attività
Riccardo Cardin
 
Diagrammi Use Case
Diagrammi Use CaseDiagrammi Use Case
Diagrammi Use Case
Riccardo Cardin
 
Introduzione a UML
Introduzione a UMLIntroduzione a UML
Introduzione a UML
Riccardo Cardin
 
Mvc e di spring e angular js
Mvc e di   spring e angular jsMvc e di   spring e angular js
Mvc e di spring e angular js
Riccardo Cardin
 
Reactive programming principles
Reactive programming principlesReactive programming principles
Reactive programming principles
Riccardo Cardin
 

More from Riccardo Cardin (7)

Design Pattern Comportamentali
Design Pattern ComportamentaliDesign Pattern Comportamentali
Design Pattern Comportamentali
 
Design Pattern Creazionali
Design Pattern CreazionaliDesign Pattern Creazionali
Design Pattern Creazionali
 
Diagrammi di Attività
Diagrammi di AttivitàDiagrammi di Attività
Diagrammi di Attività
 
Diagrammi Use Case
Diagrammi Use CaseDiagrammi Use Case
Diagrammi Use Case
 
Introduzione a UML
Introduzione a UMLIntroduzione a UML
Introduzione a UML
 
Mvc e di spring e angular js
Mvc e di   spring e angular jsMvc e di   spring e angular js
Mvc e di spring e angular js
 
Reactive programming principles
Reactive programming principlesReactive programming principles
Reactive programming principles
 

Recently uploaded

What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
kalichargn70th171
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
confluent
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
ervikas4
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
kgyxske
 
Optimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptxOptimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptx
WebConnect Pvt Ltd
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
narinav14
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Vince Scalabrino
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
aeeva
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies
 

Recently uploaded (20)

What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
 
Optimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptxOptimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptx
 
bgiolcb
bgiolcbbgiolcb
bgiolcb
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
 

Java - Concurrent programming - Thread's basics

  • 1. CONCURRENT PROGRAMMING THREAD’S BASICS PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 – 2016 rcardin@math.unipd.it
  • 2. Programmazione concorrente e distribuita SUMMARY  Introduction  Thread basics  Thread properties  Thread states  Thread interruption  Sequence diagrams 2Riccardo Cardin
  • 3. Programmazione concorrente e distribuita INTRODUCTION  Multitasking  The ability to have more than a program working at what seems like the same time  The unity of this type of programming is a process  A process has its own variables  Communication between process is accomplished using messages sent over a common channel (i.e. a socket)  Very hard to accomplish and no so performant  Types  Cooperative: CPU control is left to the processes  Time-sliced: the OS (scheduler) assigns a time slice to each process 3Riccardo Cardin
  • 4. Programmazione concorrente e distribuita INTRODUCTION  Multithread  A programming model that allows multiple threads to exists within the same context of a single process  Every process will appear to do multiple tasks  Threads share the same data and variables  Every process as a main thread  This thread can create other threads, called secondary  Every thread as a priority order (1 .. 10)  Types  Cooperative  Time-sliced: thread scheduling is left to the main thread, that uses OS utilities 4Riccardo Cardin
  • 5. Programmazione concorrente e distribuita INTRODUCTION 5Riccardo Cardin
  • 6. Programmazione concorrente e distribuita INTRODUCTION 6Riccardo Cardin Process Memory Thread 1 Task Task Thread 2 Task Thread 3 Task Threads share the same memory chunks Every thread could be reused to execute different tasksThreads are lighter than processes, even so their creation is still time- consuming Each process can execute many threads Threads are a mechanism provided by the OS
  • 7. Programmazione concorrente e distribuita DEFINITION  Multithread programming  A programming model that allows multiple threads to exists within the same context of a single process  Responsiveness  Faster execution  Lower resource consumption  Parallelization  Java has built-in support for concurrent programming 7Riccardo Cardin A thread is the smallest sequence of programmed instructions that can be managed independently. Multiple thread can exist within the same process, executing concurrently and share resources such as memory. - Wikipedia
  • 8. Programmazione concorrente e distribuita THREAD BASICS  Threads in Java are the primitives that actually execute tasks  Runnable interface describes a task you want to run, usually concurrently with others  The code of the run method will be executed in a thread  Tasks are short lived, so you don’t waste the time to start a thread 8Riccardo Cardin public interface Runnable { void run(); } Runnable task = () -> { int i = 0; while (i < 1000) i++; } new Thread(task).start(); // A thread running a task
  • 9. Programmazione concorrente e distribuita THREAD BASICS  You should decouple the task that is to be run in parallel from the mechanism of running it  You can also define a subclass of Thread, but this approach is no longer recommended  If you have many task is to expensive create a single thread for each one  Do not call the run method on Thread or Runnable instances  The task is merely executed in the same thread 9Riccardo Cardin class MyThread extends Thread { public void run() { // task code, don’t do this!!! } }
  • 10. Programmazione concorrente e distribuita THREAD BASICS 10Riccardo Cardin
  • 11. Programmazione concorrente e distribuita THREAD BASICS  The main method executes in the main thread  From the main thread they can be executed other thread, called secondary  They execute in pararrel wrt the main thread  Threads can be of two type  User threads  JVM stops when there are no more user thread executing  Deamon threads  A deamon stops when its user thread stops 11Riccardo Cardin public class Example { public static void main(String[] args) { // This code runs inside the main thread } }
  • 12. Programmazione concorrente e distribuita THREAD PROPERTIES  Thread priorities  Use setPriority method to give a thread a priority  MIN_PRIORITY = 1 and MAX_PRIORITY = 10  Don’t use priorities, they are too highly system-dependent  Deamon threads  Use setDeamon method  Its only role is to serve other threads  When only deamon threads remain, the JVM exits  Handlers for uncaught exceptions  The run method cannot throw any checked ex.  Install an UncaughtExceptionHandler to manage ex. 12Riccardo Cardin
  • 13. Programmazione concorrente e distribuita THREAD STATES  6 thread states  New  Runnable  Blocked  Waiting  Time waiting  Terminated  Use getState method  Thread.State 13 No resources associated Runnable ≠ Running
  • 14. Programmazione concorrente e distribuita THREAD STATES  New threads  Just created with the new operator. Not yet running  Runnable threads  Once the start method is invoked.  Resource creation, scheduling  run method is invoked  It may or not actually be running  DO NOT CALL RUN METHOD DIRECTLY! 14Riccardo Cardin public static void main(String[] args) { // Not concurrent, but sequential new MyThread().run(); for (int i = 0; i < 200; i++) System.out.println("Cycle - " + i); }
  • 15. Programmazione concorrente e distribuita THREAD STATES  Blocked and Waiting threads  Temporarily inactive  A thread becomes blocked when it tries to acquire an intrinsic object lock  When a thread waits for another thread to notify of a condition, it enters the waiting state  The calling of a timeout parameters causes the thread to enter the timed waiting (Thread.sleep)  A thread waits for another thread to finish, calling the join method on it  Terminated threads  It is not possible to reborn a thread in this state 15Riccardo Cardin
  • 16. Programmazione concorrente e distribuita THREADS INTERRUPTION  A thread terminates when it’s run method:  Returns by executing a return statement  After executing the last statement in method body  If an unhandled exception occurs  It is possible to send an interruption request  Use the interrupt method  Thread states becomes interrupted, but thread is not interrupted by the JVM  Thread should check whether it has been interrupted 16Riccardo Cardin while (!Thread.currentThread().isInterrupted() && more work to do) { // do more work }
  • 17. Programmazione concorrente e distribuita THREADS INTERRUPTION  Waiting for another thread to finish  Use join() or join(long millis)  An instance of the joining thread must be available  Passing a time interval to the method has the effect to limit the waiting period to millis milliseconds 17Riccardo Cardin Thread thread = new Thread(() -> { // Do some heavy work }); thread.start(); try { // Waiting for at max 1 second the termination of thread thread.join(1000L); } catch(InterruptedException e) { // thread was interrupted during sleep } finally { // cleanup, if required }
  • 18. Programmazione concorrente e distribuita THREADS INTERRUPTION  Implementing collaborative preemption  Thread.yield() notifies the system that the current thread is willing to "give up the CPU" for a while.  Thread scheduler will select a different thread to run  If no other thread is present, the statement has no effect  When to use yield()? Practically NEVER  Use Thread.sleep() (requires some self-computation)  Use synchronization mechanisms if waiting for a process or a resource 18Riccardo Cardin while ( /* more work to do */ ) { // do more work Thread.yield(); }
  • 19. Programmazione concorrente e distribuita THREADS INTERRUPTION  Interrupting a thread simply grabs its attention  Use Thread.sleep(long time) to suspend temporarily the thread  If the interrupted thread was sleeping or waiting for something, an InterruptedException is thrown  ...and the thread status is cleared! 19Riccardo Cardin try { while ( /* more work to do */ ) { // do more work Thread.sleep(delay); } } catch(InterruptedException e) { // thread was interrupted during sleep } finally { // cleanup, if required }
  • 20. Programmazione concorrente e distribuita THREADS INTERRUPTION 20Riccardo Cardin
  • 21. Programmazione concorrente e distribuita SEQUENCE DIAGRAMS  How can we reason about thread visually?  UML gives use sequence diagrams 21Riccardo Cardin Partecipant Timepassing Life line
  • 22. Programmazione concorrente e distribuita SEQUENCE DIAGRAMS 22Riccardo Cardin A sequence diagram describes the cooperation between a group of objects that have to interact with each other to fulfill an objective Definition Message Find message Internal call Return Object creation
  • 23. Programmazione concorrente e distribuita EXAMPLES 23Riccardo Cardin https://github.com/rcardin/pcd-snippets
  • 24. Programmazione concorrente e distribuita REFERENCES  Chap. 14 «Multithreading», Core Java Volume I - Fundamentals, Cay Horstmann, Gary Cornell, 2012, Prentice Hall  Thread.yield http://www.javamex.com/tutorials/threads/yield.shtml  What are the main uses of yield(), and how does it differ from join() and interrupt()? http://stackoverflow.com/questions/6979796/what-are-the-main- uses-of-yield-and-how-does-it-differ-from-join-and-interr  Chap. 10 «Concurrent Programming», Core Java for the Impatient, Cay Horstmann, 2015, Addison-Wesley 24Riccardo Cardin