public class Shared0 { private static int x = 0, y = 0;

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

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

Java Threads. COMP 585 Noteset #2 1

Threads Chate Patanothai

Concurrency in Java Prof. Stephen A. Edwards

Java Threads. Introduction to Java Threads

7. MULTITHREDED PROGRAMMING

Introduction to Java Threads

Software Practice 1 - Multithreading

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

Chapter 32 Multithreading and Parallel Programming

CMSC 330: Organization of Programming Languages

Multi-threaded programming in Java

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

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

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

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

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

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

Module - 4 Multi-Threaded Programming

Unit - IV Multi-Threading

Advanced Concepts of Programming

Multithreaded Programming

Concurrent Programming using Threads

COMP346 Winter Tutorial 4 Synchronization Semaphores

What is a thread anyway?

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

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

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

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

Synchronization in Java

Overview of Java Threads (Part 2)

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

What is a Thread? Why Multicore? What is a Thread? But a fast computer runs hot THREADS AND CONCURRENCY. Concurrency (aka Multitasking)

CS 556 Distributed Systems

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

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

Multithread Computing

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

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

Multithreaded Programming

Programming Language Concepts: Lecture 11

Basics of. Multithreading in Java

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

Synchronization synchronization.

Info 408 Distributed Applications Programming Exercise sheet nb. 4

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

Concurrent Programming

Synchronized Methods of Old Versions of Java

Unit 5 - Exception Handling & Multithreaded

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

CS11 Java. Fall Lecture 7

CS 351 Design of Large Programs Threads and Concurrency

Program #3 - Airport Simulation

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

wait with priority An enhanced version of the wait operation accepts an optional priority argument:

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking

CMSC 132: Object-Oriented Programming II

Object Oriented Programming. Week 10 Part 1 Threads

04-Java Multithreading

UNIT V CONCURRENT PROGRAMMING

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

Only one thread can own a specific monitor

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

User Space Multithreading. Computer Science, University of Warwick

Multi-threading in Java. Jeff HUANG

Component-Based Software Engineering

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Techniques of Java Programming: Concurrent Programming in Java

Chapter 19 Multithreading

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

Unit III Rupali Sherekar 2017

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

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Threads Questions Important Questions

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

JAVA. Lab 12 & 13: Multithreading

Threads, Concurrency, and Parallelism

Problems with Concurrency. February 19, 2014

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

Concurrency COMS W4115. Prof. Stephen A. Edwards Spring 2002 Columbia University Department of Computer Science

Implementing Coroutines. Faking Coroutines in Java

Advanced Programming Concurrency

Part IV Other Systems: I Java Threads

THREADS AND CONCURRENCY

THREADS & CONCURRENCY

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Concurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads

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

Concurrency Quiz: Java Threads

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data

Programming in Parallel COMP755

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

Programming Java. Multithreaded Programming

Question Points Score Total 100

CS211 Lecture: Concurrency, Threads; UML Activity Diagrams last revised October 11, 2007 Objectives

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

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

Transcription:

A race condition occurs anytime that the execution of one thread interferes with the desired behavior of another thread. What is the expected postcondition for the following bump() method? What should racehasoccurred() return? public class Shared0 { private static int x = 0, y = 0; public static void bump() throws InterruptedException { x++; Thread.currentThread().yield(); y++; public static boolean racehasoccurred() { return x!= y; This page left intentionally blank. 1

public class Race0 extends Thread { private Driver0 thedriver; public Race0(Driver0 d) { thedriver = d; public void run() { for (int i = 1; i < 1000; i++) { if (Shared0.raceHasOccurred()) System.out.print("R"); else System.out.print("."); if (i % 60 == 0) System.out.println(); Thread.currentThread().yield(); thedriver.setdonetotrue(); public class Driver0 { private boolean raceisdone = false; private Thread race0; public Driver0() { race0 = new Race0(this); race0.start(); while (!raceisdone) { Shared0.bump(); Thread.currentThread().yield(); catch (InterruptedException e) { public void setdonetotrue() { raceisdone = true; public static void main(string[] x) { new Driver0(); 2

Every Java object can be owned in one of two ways: synchronized (objectref) { // the objectref object is owned (locked) for the duration of this instruction.... synchronized returntype somemethod (parmlist) { // the this object is owned (locked) for the duration of this method call.... When a thread owns an object, any other thread attempting to gain ownership of the same object will be suspended (blocked) until the ownership is released. A instruction forms a segment of code that is mutually exclusive to all other code synchronized on the same object. synchronized methods in the same class create a monitor. wait(), notify() and notifyall() can only be called upon a owned object. (These Object methods are explained later.) Closing the earlier race condition. public class Shared1 { private static int x = 0, y = 0; public static synchronized void bump() throws InterruptedException { x++; Thread.currentThread().yield(); y++; public static synchronized boolean racehasoccurred() { return x!= y; Critical sections must be mutually exclusive in execution for correct behavior. 3

Requirements for two code segments to form critical sections with respect to each other: 1 The two segments execute concurrently. 2 The two segments share some data. 3 At least one of the segments alters the shared data. - from Object Suspend the thread, placing it in the waiting list associated with the object. (Note that the thread must have ownership prior to wait() and that ownership is relinquished by the wait().) - from Object Release one thread from the waiting list associated with the object. The released thread will attempt again to gain ownership. If the waiting list is empty, then notify() does nothing. - from Object notify() all threads in the object's waiting list. 4

threadobj = new MyThread(); New Dead return from run() threadobj.start(); threadobj.wait(); threadobj.notify(); Runnable threadobj.sleep(t); t millisec. expires Blocked threadobj.yield(); I/O completes I/O starts Often threads need to coordinate execution so that one task from some thread occurs prior to a different task in another thread. EXAMPLE (from a Three Stooges movie) Imagine three threads: MoeThread, LarryThread and CurlyThread. Each thread is responsible for executing code that does damage to the associated stooge. The proper order of damage is: 1) Moe slugs Larry. 2) Curly slaps himself. 3) Moe is punched repeatedly by another actor. 5

public class LarryThread extends Thread { public void run() { System.out.println("Larry is ready."); Shared.waitingA.synchroWait(); System.out.println("Moe slugs Larry"); Shared.waitingB.synchroNotify(); public class CurlyThread extends Thread { public void run() { System.out.println("Curly is ready."); Shared.waitingB.synchroWait(); System.out.println("Curly slaps himself."); Shared.waitingC.synchroNotify(); public class MoeThread extends Thread { public void run() { System.out.println("Moe is ready."); Shared.waitingA.synchroNotify(); Shared.waitingC.synchroWait(); System.out.println("Moe is punched by another actor."); public class Shared { public static SynchroWaiter waitinga = new SynchroWaiter(); public static SynchroWaiter waitingb = new SynchroWaiter(); public static SynchroWaiter waitingc = new SynchroWaiter();; INCORRECT SynchronizeWaiter public class SynchroWaiter { public synchronized void synchrowait() { wait(); catch (InterruptedException e) { public synchronized void synchronotify() { notify(); 6

CORRECT SynchronizeWaiter public class SynchroWaiter { private int waitcount = 0; public synchronized void synchrowait() { waitcount++; if (waitcount >= 1) wait(); catch (InterruptedException e) { public synchronized void synchronotify() { waitcount--; notify(); Producer thread monitorobj.deposit(data); Consumer thread monitorobj.remove(data); public class Monitor { private final int numberofbuffers = 100; private int buffersinuse = 0; public synchronized void deposit( Stuff data ) { while (buffersinuse == numberofbuffers) wait(); catch (InterruptedException e) { placeinnextavailablebuffer(data); buffersinuse++; notifyall(); public synchronized Stuff remove() { while (buffersinuse == 0) wait(); catch (InterruptedException e) { Stuff stuff = datafromoldestbuffer(); buffersinuse--; notifyall(); return stuff; 7

isalive() - from Thread Returns true unless the thread is dead. obj.join() - from Thread Causes the executing thread to suspend awaiting the obj thread to die. interrupt() - from Thread If the thread is blocked via wait or join, then InterruptException is thrown. If the thread is blocked for I/O, then ClosedByInterruptException is thrown. setpriority(int p) - from Thread Assigns a priority to a thread. Higher numbers mean higher priority to execute. setdaemon(boolean on) - from Thread Sets a thread as a daemon or not. Daemons can continue to run in the background when a program terminates. suspend(), resume(), stop() - from Thread All are deprecated! 8