Part IV Other Systems: I Java Threads

Similar documents
CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Threads Chate Patanothai

Monitors; Software Transactional Memory

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

Java Threads. Introduction to Java Threads

Faculty of Computers & Information Computer Science Department

Lecture 29: Java s synchronized statement

Concurrent Programming using Threads

Advanced Concepts of Programming

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

Synchronization in Java

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

Java Threads. COMP 585 Noteset #2 1

What is a thread anyway?

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Lecture 10: Introduction to Semaphores

Monitors & Condition Synchronization

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

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

Unit - IV Multi-Threading

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

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

Monitors CSCI 201 Principles of Software Development

Module - 4 Multi-Threaded Programming

COMP346 Winter Tutorial 4 Synchronization Semaphores

Monitors; Software Transactional Memory

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

Synchronization. Announcements. Concurrent Programs. Race Conditions. Race Conditions 11/9/17. Purpose of this lecture. A8 released today, Due: 11/21

Multithreaded Programming

User Space Multithreading. Computer Science, University of Warwick

Lecture 9: Introduction to Monitors

Question Points Score Total 100

Threads and Parallelism in Java

CS 361 Concurrent programming Drexel University Spring 2000 Lecture 14. The dining philosophers problem

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

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

Synchronization Lecture 24 Fall 2018

7. MULTITHREDED PROGRAMMING

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

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

Results of prelim 2 on Piazza

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

Programming in Java

Introduction to Java Threads

Two Types of Semaphores

CS 159: Parallel Processing

Synchronization synchronization.

Synchronization Lecture 23 Fall 2017

Race Conditions & Synchronization

Monitors & Condition Synchronization

Monitors & Condition Synchronisation

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

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

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

OS06: Monitors in Java

Question Points Score Total 100

Principles of Software Construction: Concurrency, Part 2

System Programming. Practical Session 4: Threads and Concurrency / Safety

5. Liveness and Guarded Methods

Michele Van Dyne MUS 204B Concurrency Issues

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

COMP 322: Fundamentals of Parallel Programming

CSCD 330 Network Programming

CMSC 330: Organization of Programming Languages

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

Concurrency in Java Prof. Stephen A. Edwards

CMSC 132: Object-Oriented Programming II

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

MVP1: Introduction to concurrency in JAVA

CS180 Review. Recitation Week 15

Software Practice 1 - Multithreading

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

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

Concurrency. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Programming Language Concepts: Lecture 11

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Programming Java. Multithreaded Programming

Concurrent Programming Benoît Garbinato

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

COE518 Lecture Notes Week 7 (Oct 17, 2011)

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Multiple Inheritance. Computer object can be viewed as

Advanced Programming Concurrency

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

CSCD 330 Network Programming

Multi-threading in Java. Jeff HUANG

CSCI 5828: Foundations of Software Engineering

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

Parallel & Concurrent Programming

Concurrency. Fundamentals of Computer Science

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

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

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

CS11 Java. Fall Lecture 7

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Programming in Parallel COMP755

Transcription:

Part IV Other Systems: I Java Threads Spring 2019 C is quirky, flawed, and an enormous success. 1 Dennis M. Ritchie

Java Threads: 1/6 Java has two ways to create threads: Create a new class derived from the Thread class and overrides its run() method. This is similar to that of ThreadMentor. Define a class that implements the Runnable interface. 2

Java Threads: 2/6 Method #1: Use the Thread class public class HelloThread extends Thread public void run() System.out.println( Hello World ); public static void main(string[] args) HelloThread t = new HelloThread(); t.start(); 3

Java Threads: 3/6 Method #2: Use the Runnable interface defined as follows: public interface Runnable public abstract void run(); 4

Java Threads: 4/6 class Foo String name; public Foo(String s) name = s; public void setname(string s) name = s; public String getname() return name; class FooBar extends Foo implements Runnable public FooBar(String s) super(s); public void run() for (int i = 0; i < 10; i++) System.out.println(getName()+ : Hello World ); public static void main(string[] args) FooBar f1 = new FooBar( Romeo ); Thread t1 = new Thread(f1); t1.start(); FooBar f2 = new FooBar( Juliet ); Thread t2 = new Thread(f2); t2.start(); 5

Java Threads: 5/6 public class Fibonacci extends Thread int n, result; public Fibonacci(int n) this.n = n; public void run() if ((n == 0) (n == 1)) result = 1; else Fibonacci f1 = new Fibonacci(n-1); Fibonacci f2 = new Fibonacci(n-2); f1.start(); f2.start(); try f1.join(); f2.join(); catch (InterruptedException e) ; result = f1.getresult()+f2.getresult(); public int getresult() return result; Part 1/2 6

Java Threads: 6/6 public static void main(string [] args) Fibonacci f1 = new Fibonacci(Integer.parseInt(args[0])); f1.start(); try f1.join(); catch (InterruptedException e) ; System.out.println( Ans = +f1.getresult()); Part 2/2 7

The synchronized Keyword The synchronized keyword of a block implements mutual exclusion. public class Counter private int count = 0; public int inc() synchronized(this) return ++count; this is a critical section 8

Java ReentrantLock: 1/2 A lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. A ReentrantLock is similar to the synchronized keyword. You may use lock() to acquire a lock and unlock() to release a lock. There are other methods (e.g., trylock()). 9

Java ReentrantLock: 2/2 The following is a typical use of locks in Java. Lock mylock = new ReentrantLock(); mylock.lock(); // acquire a lock try // in critical section now // catch exceptions and // restore invariants if needed finally mylock.unlock(); 10

Java wait() and notify(): 1/7 Method wait() causes a thread to release the lock it is holding on an object, allowing another thread to run. wait() should always be wrapped in a try block because it throws IOException. wait() can only be invoked by the thread that owns the lock on the object. The thread that calls wait() becomes inactive until it is notified. Note that actual situation can be more complex than this. 11

Java wait() and notify(): 2/7 A thread uses the notify() method of an object to release a waiting thread or the notifyall() method to release all waiting threads. After notify() or notifyall(), a thread may be picked by the thread scheduler and resumes its execution. Then, this thread regains its lock automatically. Using notify() and notifyall() as the last statement can avoid many potential problems. 12

Java wait() and notify(): 3/7 public class Counter implements BoundedCounter protected long count = MIN; public synchronized long value() return count; public synchronized long inc() awaitinc(); setcount(count+1); public synchronized long dec() awaitdec(); setcount(count-1); protected synchronized void setcount(long newval) count = newval; notifyall(); protected synchronized void awaitinc() while (count >= MAX) try wait(); catch(interruptedexception e); protected synchronized void awaitdec() while (count <= MIN) try wait(); catch(interruptedexception e); 13

Java wait() and notify(): 4/7 public final class CountingSemaphore private int count = 0; public CountingSemaphore(int initval) count = initval; public synchronized void P() // semaphore wait count--; while (count < 0) try wait(); catch (InterruptedException e) they are different from our definition can you see they are equivalent? public synchronized void V() // semaphore signal count++; notify(); why is testing for count <= 0 unnecessary? 14

Java wait() and notify(): 5/7 public class Buffer implements BoundedBuffer protected Object[] buffer; protected int in; protected int out; protected int count; public Buffer(int size) throws IllegalArgumentException if (size <= 0) throw new IllegalArgumentException(); buffer = new Object[size]; public int GetCount() return count; public int capacity() return Buffer.length; // methods put() and get() Part 1/3 15

Java wait() and notify(): 6/7 public synchronized void put(object x) while (count == Buffer.length) try wait(); catch(interruptedexception e); Buffer[in] = x; in = (in + 1) % Buffer.length; if (count++ == 0) notifyall(); Part 2/3 16

Java wait() and notify(): 7/7 public synchronized void get(object x) while (count == 0) try wait(); catch(interruptedexception e); Object x = Buffer[out]; Buffer[out] = null; out = (out + 1) % Buffer.length; if (count-- == Buffer.length) notifyall(); return x; Part 3/3 17

The End 18