1 Java Programming Java Programming II Concurrent Programming: Threads ( II)

Slides:



Advertisements
Similar presentations
– R 7 :: 1 – 0024 Spring 2010 Parallel Programming 0024 Recitation Week 7 Spring Semester 2010.
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.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
CS Concurrent Programming CS 3331 Fall 2009.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Practice Session 7 Synchronization Liveness Guarded Methods Model
Concurrency (3) CSE 132. iClicker/WUTexter Question The following four numbers are in 8-bit 2’s complement form: Which.
CS 11 java track: lecture 7 This week: Web tutorial:
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
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.
ThreadThread Thread Basics Thread Synchronization Animations.
Definitions Process – An executing program
Jan Java Threads Yangjun Chen Dept. Business Computing University of Winnipeg.
Threads Just Java: C10–pages 251- C11–pages 275-
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
More Multithreaded Programming in Java David Meredith Aalborg University.
Multithreading.
Lecture 4 : JAVA Thread Programming
Internet Software Development More stuff on Threads Paul Krause.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
1 Java Threads and Synchronization Review Modified from slides taken from
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
Threading Eriq Muhammad Adams J
Producer-Consumer Problem The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue.bufferqueue.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Module 6: Process Synchronization Codes.
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.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
CS 151: Object-Oriented Design November 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Component-Based Software Engineering Understanding Thread Safety Paul Krause.
Advanced Tools for Multi- Threads Programming Avshalom Elmalech Eliahu Khalastchi 2010.
Producer/Consumer CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Distributed and Parallel Processing George Wells.
Multithreading / Concurrency
Multi Threading.
Multithreading Chapter 9.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Synchronization Lecture 23 – Fall 2017.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Multithreading.
13: Concurrency Definition:  A thread is a single sequential flow of control within a program. Some texts use the name lightweight process instead of thread.
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Component-Based Software Engineering
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 Java Programming Java Programming II Concurrent Programming: Threads ( II)

2 Java Programming Contents  Synchronized statements  wait, notifyAll, and notify Methods  A Producer and Consumer Example  Thread Scheduling

3 Java Programming Synchronized Statements  Synchronized Statements The synchronized statement enables to execute synchronized code that acquires the lock of any object, not just the current object, or for durations less than the entire invocation of a method. /** make all elements in the array non-negative */ pubic static void abs(int[] values) { synchronized (values) { for (int i=0; i < values.length; i++) { if (values[i] < 0) values[i] = -values[i]; } The array is not changed during execution by any other code that is similarly synchronized on the values array synchronized (expr) { statements } An object whose lock is to be acquired To execute when the lock is obtained.

4 Java Programming Synchronized Statements  A necessity of synchronize statement  In MsLunch, the c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); } --- public class MsLunch { private long c1 = 0; private long c2 = 0; private Object lock1 = new Object(); private Object lock2 = new Object(); public void inc1() { synchronized(lock1) { c1++; } public void inc2() { synchronized(lock2) { c2++; } needs to synchronize changes to lastName and nameCount also needs to avoid synchronizing invocations of other objects' methods.

5 Java Programming Synchronized Statements  Advantages of the synchronized statement Can define a synchronized region of code that is smaller than a method. Allow to synchronize on objects other than this, allowing a number of different synchronization designs to be implemented. A finer granularity of locking. Use for an inner object to synchronize on its enclosing object: class SeparateGroups { private double aVal = 0.0; private double bVal = 1.1; protected final Object lockA = new Object(); protected final Object lockB = new Object(); public double getA() { synchronized(lockA) { return aVal; } } public void setA(double val) { synchronized (lockA) { aVal = val; } } public double getB() { synchronized(lockB) { return bVal; } } public void setB(double val) { synchronized (lockB) { bVal = val; } } public void reset() { synchronized (lockA) { synchronized (lockB) { aVal = bVal = 0.0; } } You can define separate objects to be used as locks for each such group using synchronized statements

6 Java Programming Deadlock public synchronized void bowBack(Friend bower) { System.out.format("%s: %s has bowed back to me!%n“, this.name, bower.getName()); } public static void main(String[] args) { final Friend alphonse = new Friend("Alphonse"); final Friend gaston = new Friend("Gaston"); new Thread(new Runnable() { public void run() { alphonse.bow(gaston); } }).start(); new Thread(new Runnable() { public void run() { gaston.bow(alphonse); } }).start(); }  Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.  Alphonse and Gaston are friends, and great believers in courtesy.  Bowing Rule: When you bow to a friend, you must remain bowed until your friend has a chance to return the bow.  Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time public class Deadlock { static class Friend { private final String name; public Friend(String name) { this.name = name; } public String getName() { return this.name; } public synchronized void bow(Friend bower) { System.out.format("%s: %s has bowed to me!%n", this.name, bower.getName()); bower.bowBack(this); }

7 Java Programming Wait, notifyAll, and notify  The wait() method The wait() method allows a thread that is executing a synchronized method or statement block on that object to release the lock and wait for a notification from another thread.  The notify() method The notify() method allows a thread that is executing a synchronized method or statement block to notify another thread that is waiting for a lock on this object.  Standard Pattern of Wait synchronized void doWhenCondition() { while(!condition) wait(); … Do what must be done when the condition is true… }  Notification synchronized void changeCondition() { … change some value used in a condition test…. notifyAll(); // or notify() }

8 Java Programming Wait, notifyAll, and notify Class PrintQueue { private SinglLinkQueue queue = new SingleLinkQueue (); public synchronized void add(PrintJob j) { queue.add(j); notifyAll(); // Tell waiters: print job added } public synchronized PrintJob remove() throws InterruptedException { while (queue.size() == 0) wait(); // Wait for a print job return queue.remove(); }

9 Java Programming Producer & Consumer Example Producers Consumers

10 Java Programming Producer & Consumer Example class Producer extends Thread { Queue queue; Producer(Queue queue) { this.queue = queue; } public void run() { int i = 0; while(true) { queue.add(i++); } class Consumer extends Thread { String str; Queue queue; Consumer(String str, Queue queue) { this.str = str; this.queue = queue; } public void run() { while(true) { System.out.println(str + ": " + queue.remove()); } class Queue { private final static int SIZE = 10; int array[] = new int[SIZE]; int r = 0; int w = 0; int count = 0; synchronized void add(int i) { while(count == SIZE) { try { wait(); } catch(InterruptedException ie) { ie.printStackTrace(); System.exit(0); } array[w++] = i; if (w >= SIZE) w = 0; ++count; notifyAll(); } Now, Queue is full, wait until a consumer use a element, so the queue has a space. Notification to some consumers waiting for element(s) the Producer provides

11 Java Programming Producer & Consumer Example synchronized int remove() { while(count == 0) { try { wait(); } catch(InterruptedException ie) { ie.printStackTrace(); System.exit(0); } int element = array[r++]; if (r >= SIZE) r = 0; --count; notifyAll(); return element; } class ProducerConsumers { public static void main(String args[]) { Queue queue = new Queue(); new Producer(queue).start(); new Consumer("ConsumerA", queue).start(); new Consumer("ConsumerB", queue).start(); new Consumer("ConsumerC", queue).start(); } Now, there is no element to remove, and wait until some element(s) come in to the queue.

12 Java Programming Thread Scheduling  Ending Thread Execution The run method returns normally public static void sleep(long millis) public static void sleep(long millis, int nanos) public static void yield() class Babble extends Thread { static boolean doYield; static int howOften; private String word; Babble(String whatToSay) { word = whatToSay; } public void run() { for(int i=0; i<howOften; i++) { System.out.println(word); if (doYield) Thread.yield(); // let other threads run } public static void main(String[] args) { doYield = new Boolean(args[0]).booleanValue(); howOften = Integer.parseInt(args[1]); // create a thread for each world for (int i=2; i < args.length; i++) new Babble(args[i]).start(); } Run: % java Babble false 2 Did DidNot Result: Did DidNot