Multithreading Chapter 23.

Slides:



Advertisements
Similar presentations
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Advertisements

EEE 435 Principles of Operating Systems Interprocess Communication Pt II (Modern Operating Systems 2.3)
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
 2005 Pearson Education, Inc. All rights reserved Multithreading.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading The objectives of this chapter are:
Threads Daniel Bennett, Jeffrey Dovalovsky, Dominic Gates.
1 L49 Multithreading (1). 2 OBJECTIVES  What threads are and why they are useful.  How threads enable you to manage concurrent activities.  The life.
 2007 Pearson Education, Inc. All rights reserved. 1 Ch23 Multithreading: OBJECTIVES In this chapter you will learn:  What threads are and why they are.
Chapter 2: Processes Topics –Processes –Threads –Process Scheduling –Inter Process Communication (IPC) Reference: Operating Systems Design and Implementation.
1 CS318 Project #3 Preemptive Kernel. 2 Continuing from Project 2 Project 2 involved: Context Switch Stack Manipulation Saving State Moving between threads,
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 L50 Multithreading (2). 2 OBJECTIVES  What producer/consumer relationships are and how they are implemented with multithreading.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Definitions Process – An executing program
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Collage of Information Technology University of Palestine Advanced programming MultiThreading 1.
Java Programming: Advanced Topics
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
1 Concurrent Languages – Part 1 COMP 640 Programming Languages.
Java Threads Representation and Management of Data on the Internet.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
Threaded Programming in Python Adapted from Fundamentals of Python: From First Programs Through Data Structures CPE 401 / 601 Computer Network Systems.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading Chapter Introduction Consider ability of _____________ to multitask –Breathing, heartbeat, chew gum, walk … In many situations we.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Multithreading [Modified]
Multithreading in JAVA
Java Thread and Memory Model
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
1 Mouse Events See Figure See Example in Figure 11.28,
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
CS203 Programming with Data Structures Introduction to Threads and Synchronization California State University, Los Angeles.
Java Thread Programming
Multithreading The objectives of this chapter are:
Chapter 4 – Thread Concepts
Multithreading / Concurrency
Threaded Programming in Python
Chapter 30 Multithreading and Parallel Programming
Multithreading.
Chapter 4 – Thread Concepts
Multithreaded Programming in Java
Chapter 19 Java Never Ends
23 Multithreading.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading.
Multithreading.
Multithreaded Programming
Threads Chapter 4.
Multithreading in java.
NETWORK PROGRAMMING CNET 441
CS333 Intro to Operating Systems
Threads and Multithreading
Multithreading The objectives of this chapter are:
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multithreading Chapter 23

What You Will Learn Thread States Thread Synchronization Producers and consumers

Introduction Consider ability of human body to multitask Breathing, heartbeat, chew gum, walk … In many situations we need a computer to multitask Concurrency normally available in OS primitives Java provides built-in multithreading Multithreading improves the performance of some programs

Thread States: Life Cycle of a Thread View diagram, Figure 23.1 new state New thread begins its life cycle in the new state Remains in this state until program starts the thread, placing it in the runnable state runnable state A thread in this state is executing its task waiting state A thread transitions to this state to wait for another thread to perform a task

Thread States: Life Cycle of a Thread View diagram, Figure 23.1 timed waiting state A thread enters this state to wait for another thread or for an amount of time to elapse A thread in this state returns to the runnable state when it is signaled by another thread or when the timed interval expires terminated state A runnable thread enters this state when it completes its task

Operating System View Of runnable State ready state Not waiting for another thread Waiting for the operating system to assign the thread a processor

Operating System View Of runnable State running state Currently has a processor and is executing Often executes for a small amount of processor time called a time slice or quantum before transitioning back to the ready state

Thread Priorities and Thread Scheduling Java thread priority Priority in range 1-10 Timeslicing Each thread assigned time on the processor (called a quantum) Keeps highest priority threads running

Priorities and Scheduling Thread.MAX_PRIORITY Priorities and Scheduling

Creating and Executing Threads Runnable interface Preferred means of creating a multithreaded application Declares method run Executed by an object that implements the Executor interface Executor interface Declares method execute Creates and manages a group of threads called a thread pool

Creating and Executing Threads ExecutorService interface Subinterface of Executor that declares other methods for managing the life cycle of an Executor Can be created using static methods of class Executors Method shutdown ends threads when tasks are completed

Creating and Executing Threads Executors class Method newFixedThreadPool creates a pool consisting of a fixed number of threads Method newCachedThreadPool creates a pool that creates new threads as they are needed

Creating and Executing Threads PrintTask class Figure 23.4 RunnableTester, Figure 23.5 Demonstrates Constructing Thread objects Using Thread methods start and sleep Creates 3 equal priority threads Each is put to sleep for random number of milliseconds When awakened, it displays name, etc.

Producers and Consumers Generating output Consumer Receives and processes the output

Synchronization Problem Sometimes the producer gets too far ahead of the consumer The objects produced fill up the holding area (buffer) The producer must wait for space to place objects Sometimes the consumer gets ahead of the producer There are no objects to be processed (empty buffer) The consumer must wait for the producer

Thread Synchronization Provided to the programmer with mutual exclusion Exclusive access to a shared object Implemented in Java using locks Lock interface lock method obtains the lock, enforcing mutual exclusion unlock method releases the lock Class ReentrantLock implements the Lock interface

Thread Synchronization Condition variables If a thread holding the lock cannot continue with its task until a condition is satisfied, the thread can wait on a condition variable Create by calling Lock method newCondition Represented by an object that implements the Condition interface

Thread Synchronization Condition interface Declares methods await, to make a thread wait, signal, to wake up a waiting thread, and signalAll, to wake up all waiting threads

Producer/Consumer Relationship without Synchronization Buffer Shared memory region Producer thread Generates data to add to buffer Calls wait if consumer has not read previous message in buffer Writes to empty buffer and calls notify for consumer Consumer thread Reads data from buffer Calls wait if buffer empty Synchronize threads to avoid corrupted data

Producer/Consumer Relationship without Synchronization View source code which establishes Buffer, Figure 23.6 An interface which specifies get and set methods Producer, Figure 23.7 Subclass of Thread Uses a shared Buffer object Method run is overridden from Thread class Uses Buffer.set() method Consumer, Figure 23.8 Also a subclass of Thread, also uses shared Buffer Uses the Buffer.get() method

Producer/Consumer Relationship without Synchronization View Figure 23.9 which implements the Buffer interface Implements the get and set methods This UnsynchronizedBuffer object is used in Figure 23.10 program Buffer object declared, instantiated Also Producer and Consumer objects Both threads call method start()

Producer/Consumer Relationship without Synchronization Example randomly called producer and consumer You should note that in some cases the data was incorrect Consumer reads values before producer generates Consumer misses a value Consumer reads same value multiple times We need to deal with problem so data is not corrupted

Producer/Consumer Relationship with Synchronization Solution is to synchronize the producer and consumer objects Figure 23.11 implements a buffer and synchronizes Consumer consumes only after produces a value Producer produces a value only after consumer consumes previous value produced Condition variable occupiedBufferCount determines whose turn it is Program which uses this, Figure 23.12

Using Thread Methods Create Wait class Has static methods Provide capability to have another application pause for a certain amount of time Note Example to act as a simple timer.

Circular Buffer Features Caveats Multiple memory cells Produce item if one or more empty cells Consume item if one or more filled cells Caveats Producer and consumers must be relatively same speed Otherwise buffer fills up or stays empty Synchronization still necessary Seek to optimize buffer size minimizes thread-wait time

Circular Buffer Circular Buffer class Figure 23.13 Lock for mutual exclusion Condition variables to control writing and reading Circular buffer; provides three spaces for data Obtain the lock before writing data to the circular buffer Wait until a buffer space is empty Impose circularity of the buffer Signal waiting thread when to read data from buffer Release lock

Circular Buffer Circular Buffer test, Figure 23.14 Create instance of circular buffer Execute producer, consumer in separate threads

Daemon Threads Run for benefit of other threads Do not prevent program from terminating Garbage collector is a daemon thread Set daemon thread with method setDaemon Must be done at start time Do not assign critical tasks to daemon thread Will be terminated without warning May prevent those tasks from completing properly

Runnable Interface May be necessary to extend a class that already extends a class other than Thread Java does not allow a class to extend more than one class at a time Implement Runnable for multithreading support Program that uses a Runnable object to control a thread Creates a Thread object Associates the Runnable object with that Thread class

Runnable Interface Illustration of using a Runnable interface Figure 23.18 Note methods start, stop, run