Threads. Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence.

Slides:



Advertisements
Similar presentations
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Advertisements

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Monitors & Blocking Synchronization 1. Producers & Consumers Problem Two threads that communicate through a shared FIFO queue. These two threads can’t.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
COS 461 Fall 1997 Concurrent Programming u Traditional programs do one thing at a time. u Concurrent programs do several things at once. u Why do this?
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Software Engineering Oct-01 #11: All About Threads Phil Gross.
1 Threads. 2 Introduction s/index.html
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
Definitions Process – An executing program
Race Conditions CS550 Operating Systems. Review So far, we have discussed Processes and Threads and talked about multithreading and MPI processes by example.
Java Threads. Introduction Process 1 Processes and Threads Environment Stack Code Heap CPU State Process 2 Environment Stack Code Heap CPU State.
Copyright © 1998 Alex Chaffee Building a Robust Multithreaded Server in Java Alexander Day Chaffee jGuru Training by the MageLang Institute
CS Introduction to Operating Systems
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Java Programming: Advanced Topics
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Java Threads DBI – Representation and Management of Data on the Internet.
111 © 2002, Cisco Systems, Inc. All rights reserved.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
C# I 1 CSC 298 Threads. C# I 2 Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The execution.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
1 cs Process 1 Processes and Threads Environment Stack Code Heap CPU State Process 2 Environment Stack Code Heap CPU State cs
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
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.
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
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.
Multi-Threading in Java
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 Dr.A.Srinivas PES Institute of Technology Bangalore, India
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
1 Ivan Marsic Rutgers University LECTURE 19: Concurrent Programming.
Java Threads DBI – Representation and Management of Data on the Internet.
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.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
6/11/2016 DEPT OF CSE 1 JAVA. 6/11/2016 DEPT OF CSE 2 MULTITHREADED PROGRAMMING.
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.
Distributed and Parallel Processing George Wells.
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
Multithreading / Concurrency
Multi Threading.
Multithreaded Programming in Java
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Threads cs
Multithreading.
Multithreading 2 Lec 24.
Multithreading.
Computer Science 2 06A-Java Multithreading
NETWORK PROGRAMMING CNET 441
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads

Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence of method calls

The Thread Object A thread is not an object A Thread is an object void start() –Creates a new thread and makes it runnable void run() –The new thread begins its life inside this method

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Runnable Interface A helper to the thread object The Thread object’s run() method calls the Runnable object’s run() method Allows threads to run inside any object, regardless of inheritance

Runnable Example Talker talker = new Talker(); Thread t = new Thread(talker); t.Start(); --- class Talker implements Runnable { public void run() { while (true) { System.out.println(“yakitty yak”); }

Thread Lifecycle Born Blocked Runnable Dead stop() start() stop() Active block on I/O I/O available JVM sleep(500) wake up suspend() resume() wait notify

Blocking Threads When reading from a stream, if input is not available, the thread will block Thread is suspended (“blocked”) until I/O is available Allows other threads to automatically activate When I/O available, thread wakes back up again –Becomes “runnable” –Not to be confused with the Runnable interface

Thread Scheduling In general, the runnable thread with the highest priority is active (running) Java is priority-preemptive –If a high-priority thread wakes up, and a low- priority thread is running –Then the high-priority thread gets to run immediately Allows on-demand processing –Efficient use of CPU

Thread Starvation If a high priority thread never blocks Then all other threads will starve Must be clever about thread priority

Thread Priorities: General Strategies Threads that have more to do should get lower priority Counterintuitive Cut to head of line for short tasks Give your I/O-bound threads high priority –Wake up, immediately process data, go back to waiting for I/O

Race Conditions Two threads are simultaneously modifying a single object Both threads “race” to store their value In the end, the last one there “wins the race” (Actually, both lose)

Race Condition Example class Account { int balance; public void deposit(int val) { int newBal; newBal = balance + val; balance = newBal; }

Thread Synchronization Language keyword: synchronized Takes out a monitor lock on an object –Exclusive lock for that thread If lock is currently unavailable, thread will block

Thread Synchronization Protects access to code, not to data –Make data members private –Synchronize accessor methods Puts a “force field” around the locked object so no other threads can enter Actually, it only blocks access to other synchronizing threads

Thread Deadlock If two threads are competing for more than one lock Example: bank transfer between two accounts –Thread A has a lock on account 1 and wants to lock account 2 –Thread B has a lock on account 2 and wants to lock account 1

Avoiding Deadlock No universal solution Ordered lock acquisition Encapsulation (“forcing directionality”) Spawn new threads Check and back off Timeout Minimize or remove synchronization

Wait and Notify Allows two threads to cooperate Based on a single shared lock object

Wait and Notify: Code Consumer: synchronized (lock) { while (!resourceAvailable()) { lock.wait(); } consumeResource(); }

Wait and Notify: Code Producer: produceResource(); synchronized (lock) { lock.notifyAll(); }

Wait/Notify Sequence Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }

Wait/Notify Sequence Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }

Wait/Notify Sequence Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }

Wait/Notify Sequence Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }

Wait/Notify Sequence Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }

Wait/Notify Sequence Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }

Wait/Notify Sequence Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }

Wait/Notify Sequence Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }

Wait/Notify Sequence Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }

Wait/Notify Sequence Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }

Wait/Notify Sequence Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }

Wait/Notify: Details Often the lock object is the resource itself Sometimes the lock object is the producer thread itself

Wait/Notify: Details Must loop on wait(), in case another thread grabs the resource... –After you are notified –Before you acquire the lock and return from wait() Use lock.notifyAll() if there may be more than one waiting thread

Wait/Notify Example: Blocking Queue class BlockingQueue extends Queue { public synchronized Object remove() { while (isEmpty()) { wait(); // really this.wait() } return super.remove(); } public synchronized void add(Object o) { super.add(o); notifyAll(); // this.notifyAll() }