SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

Similar documents
SUMMARY FUTURES CALLABLES CONCURRENT PROGRAMMING THREAD S ADVANCED CONCEPTS

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

ASSERTIONS AND LOGGING

Object Oriented Programming. Week 10 Part 1 Threads

CS 556 Distributed Systems

7. MULTITHREDED PROGRAMMING

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Unit - IV Multi-Threading

Multithreaded Programming

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Multithreading Pearson Education, Inc. All rights reserved.

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

CMSC 132: Object-Oriented Programming II. Threads in Java

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Java Threads. Written by John Bell for CS 342, Spring 2018

CIS233J Java Programming II. Threads

Module - 4 Multi-Threaded Programming

Animation Part 2: MoveableShape interface & Multithreading

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Threads Chate Patanothai

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

Performance Throughput Utilization of system resources

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

Object Oriented Programming (II-Year CSE II-Sem-R09)

Contents. 6-1 Copyright (c) N. Afshartous

Advanced Concepts of Programming

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India

Multithreaded Programming

Techniques of Java Programming: Concurrent Programming in Java

Multithreading using Java. Dr. Ferdin Joe John Joseph


What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Concurrent Computing CSCI 201 Principles of Software Development

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Multithreaded Programming

CS360 Lecture 12 Multithreading

Software Practice 1 - Multithreading

By: Abhishek Khare (SVIM - INDORE M.P)

UNIT V CONCURRENT PROGRAMMING

Java Threads. COMP 585 Noteset #2 1

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

What is a thread anyway?

JAVA - MULTITHREADING

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Threads in Java (Deitel & Deitel)

04-Java Multithreading

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Process Characteristics. Threads Chapter 4. Process Characteristics. Multithreading vs. Single threading

Threads Chapter 4. Reading: 4.1,4.4, 4.5

Chapter 3 Process Description and Control

G52CON: Concepts of Concurrency

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

Unit III Rupali Sherekar 2017

Java s Implementation of Concurrency, and how to use it in our applications.

Advanced Programming Concurrency

JAVA. Lab 12 & 13: Multithreading

Multi-threading in Java. Jeff HUANG

Amity School of Engineering

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

Unit 5 - Exception Handling & Multithreaded

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Threads Questions Important Questions

CS 351 Design of Large Programs Threads and Concurrency

Multithreaded Programming

SUMMARY INTRODUCTION REMOTE METHOD INVOCATION

CSCD 330 Network Programming

Concurrent Programming using Threads

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Object-Oriented Programming Concepts-15CS45

Programming in Java

Synchronization synchronization.

User Space Multithreading. Computer Science, University of Warwick

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

Multithread Computing

Robotics and Autonomous Systems

CSCD 330 Network Programming

Synchronization in Concurrent Programming. Amit Gupta

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

THREADS AND MULTITASKING ROBOTS

ROBOTICS AND AUTONOMOUS SYSTEMS

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Java Threads. Introduction to Java Threads

CST242 Concurrency Page 1

Producing Production Quality Software. Lecture 12: Concurrent and Distributed Programming Prof. Arthur P. Goldberg Fall, 2004

Introduction to Java Threads

MVP1: Introduction to concurrency in JAVA

CS211 Lecture: Concurrency, Threads; UML Activity Diagrams last revised October 5, 2009 Objectives

Model Requirements and JAVA Programs MVP 2 1

Chapter 32 Multithreading and Parallel Programming

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Transcription:

SUMMARY CONCURRENT PROGRAMMING THREAD S BASICS PROGRAMMAZIONE CONCORRENTE E DISTR. Introduction Thread basics Thread properties Thread states Thread interruption Sequence diagrams Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 2016 rcardin@math.unipd.it 2 INTRODUCTION 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 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 3 4

INTRODUCTION INTRODUCTION Threads are lighter than processes, even so their creation is still timeconsuming Every thread could be reused to execute different tasks Thread 2 Thread 3 Threads share the same memory chunks Threads are a mechanism provided by the OS Memory Thread 1 Process Each process can execute many threads 5 6 DEFINITION THREAD BASICS 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 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 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 public interface Runnable { void run(); s are short lived, so you don t waste the time to start a thread Runnable task = () -> { int i = 0; while (i < 1000) i++; new Thread(task).start(); // A thread running a task 7 8

THREAD BASICS 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 class MyThread extends Thread { public void run() { // task code, don t do this!!! Do not call the run method on Thread or Runnable instances The task is merely executed in the same thread 9 10 THREAD BASICS THREAD PROPERTIES The main method executes in the main thread public class Example { public static void main(string[] args) { // This code runs inside 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 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. 11 12

THREAD STATES THREAD STATES 6 thread states New Runnable Blocked Waiting Time waiting Terminated Use getstate method Thread.State Runnable Running No resources associated 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! 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); 13 14 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 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 while (!Thread.currentThread().isInterrupted() && more work to do) { // do more work 15 16

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 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 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 while ( /* more work to do */ ) { // do more work Thread.yield(); When to use yield()? Practically NEVER Use Thread.sleep() (requires some self computation) Use synchronization mechanisms if waiting for a process or a resource 17 18 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! try { while ( /* more work to do */ ) { // do more work Thread.sleep(delay); catch(interruptedexception e) { // thread was interrupted during sleep finally { // cleanup, if required 19 20

SEQUENCE DIAGRAMS How can we reason about thread visually? UML gives use sequence diagrams SEQUENCE DIAGRAMS Definition A sequence diagram describes the cooperation between a group of objects that have to interact with each other to fulfill an objective Partecipant Life line Time passing Find message Message Object creation Internal call Return 21 22 EXAMPLES REFERENCES https://github.com/rcardin/pcd snippets 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 mainuses 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 23 24