Programming with Shared Memory Java Threads and Synchronization

Slides:



Advertisements
Similar presentations
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.
Advertisements

Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Concurrency and Thread Yoshi. Two Ways to Create Thread Extending class Thread – Actually, we need to override the run method in class Thread Implementing.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Slides 8c-1 Programming with Shared Memory Java Threads and Synchronization Review The following notes are based upon the Java tutorial at
1 OS Support for Building Distributed Applications: Multithreaded Programming using Java Threads Rajkumar Buyya Grid Computing and Distributed Systems.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
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.
© 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.
Multithreading.
1 OS Support for Building Distributed Applications: Multithreaded Programming using Java Threads Dr. Rajkumar Buyya Cloud Computing and Distributed Systems.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Lecture 4 : JAVA Thread Programming
1 Java Threads and Synchronization Review Modified from slides taken from
 Traditionally, a process in an operating system consists of an execution environment and a single thread of execution (single activity).  However,
1 Multithreaded Programming using Java Threads Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Computer Engineering Rabie A. Ramadan Lecture 8. Agenda 2 Introduction Thread Applications Defining Threads Java Threads and States Priorities Accessing.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 OS Support for Building Distributed Applications: Multithreaded Programming using Java Threads.
1 Multithreaded Programming using Java Threads Prof. Rajkumar Buyya Cloud Computing and Distributed Systems (CLOUDS) Laboratory Dept. of Computer Science.
Threads.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Java Thread and Memory Model
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.
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.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Multithreaded Programming using Java Threads
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.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
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.
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.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Advanced Programming Concurrency and Threads Advanced Programming. All slides copyright: Chetan Arora.
1 Multithreading in Java THETOPPERSWAY.COM. 2 Outline  Multithreading & Thread Introduction  Creating threads  Thread Life Cycle  Threads priorities.
Java Thread Programming
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Multi Threading.
Multithreading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Multithreading in Java
Chapter 19 Java Never Ends
EE 422C Multithreading & Parallel Programming
Threads Chate Patanothai.
Exception Handling Visit for more Learning Resources.
CNT 4007C Project 2 Good morning, everyone. In this class, we will have a brief look at the project 2. Project 2 is basically the same with project 1.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Programming with Shared Memory Java Threads and Synchronization
برنامه‌نویسی چندنخی Multi-Thread Programming
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
Representation and Management of Data on the Internet
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Programming with Shared Memory Java Threads and Synchronization Brief Review ITCS4145/5145, Parallel Programming B. Wilkinson July 2, 2012 slides 8c.ppt.

Thread class Each thread is an object of the Thread class. Java tutorial* says: “Each thread is associated with an instance of the class Thread.” Java provide two basic ways to creates a thread: Define a class that is derived class of the class Thread. Make your class implement the Runnable interface * http://java.sun.com/docs/books/tutorial/essential/concurrency/

Simplest way is: Define a class that is derived class of the class Thread. Object of this class is a thread. Provide the method called run (which will override the inherited run method, which does nothing). The run method defines the code for the thread. Invoke the start method, which initiates the computation of the thread

Example public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[ ]) { HelloThread myThread = new HelloThread(); myThread.start(); Java entry point Create Thread object Start thread and execute run method

2. Make your class explicitly implement the Runnable interface The Thread class actually implements the interface called Runnable. The Runnable interface defines the single method, run, meant to contain the code executed in the thread. Alternate more powerful way to create threads: 2. Make your class explicitly implement the Runnable interface

Explicitly Implementing Runnable Interface Example Explicitly Implementing Runnable Interface public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[ ]) { HelloRunnable myThread = new HelloRunnable(); // Runnable object Thread tr = new Thread(myThread); // Create Thread object tr.start(); // Start thread and execute run method Runnable object

Advantage is Runnable object can subclass a class other than Thread, i Advantage is Runnable object can subclass a class other than Thread, i.e.: public class MyRunnable extends SomeClass implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[ ]) { HelloRunnable myThread = new HelloRunnable(); Thread tr = new Thread(myThread); tr.start(); Note: both Thread class and Runnable interface are part of the standard Java libraries (java.lang package)

A Program with Three Java Threads using 1st method class A extends Thread { public void run() { for(int i=1;i<=5;i++) System.out.println("\t From ThreadA: i= "+i); System.out.println("Exit from A"); } class B extends Thread { for(int j=1;j<=5;j++) System.out.println("\t From ThreadB: j= "+j); System.out.println("Exit from B"); class C extends Thread { for(int k=1;k<=5;k++) System.out.println("\t From ThreadC: k= "+k); System.out.println("Exit from C"); class ThreadTest { public static void main(String args[]) { new A().start(); new B().start(); new C().start(); Based on Raj Buyya’s slides

Sample Output Run 2 From ThreadA: i= 1 From ThreadA: i= 2 Exit from A From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5 Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5 Exit from B Run 2 From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5 Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5 Exit from B Exit from A

Thread class Various instance and class methods, setters and getters: sleep() … Instance methods: destroy() interrupt() join() start() Depreciated methods (unsafe and can cause deadlock) resume(), stop() suspend()

Thread.sleep causes the current thread to suspend execution for a specified period. Example Sleep to print messages at four-second intervals: public class SleepMessages { public static void main(String args[]) throws InterruptedException { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" }; for (int i = 0; i < importantInfo.length; i++) { Thread.sleep(4000); //Pause for 4 seconds System.out.println(importantInfo[i]); //Print a message } exception that sleep throws when another thread interrupts current thread while sleep is active. Not caught in sample code.

Java Synchonization Example Java provides Synchronized keyword to methods that cause only one invocation of a synchronized method on the same object at a time. Example public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; public synchronized int value() { return c;

Implementation of Java synchronization Every object has an intrinsic lock associated with it. A thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it is done with them.

Example using synchronized methods On-line banking Suppose an account can be accessed potentially simultaneously by different entities - maybe a joint account, maybe automatic debits, … Suppose three entities each trying to perform an operation, either: deposit() withdraw() enquire()

Synchronized account methods class Account { int balance; // if 'synchronized' is removed, outcome unpredictable public synchronized void deposit( ) { balance += deposit_amount; } public synchronized void withdraw( ) { balance -= deposit_amount; public synchronized void enquire( ) { … // display balance.

Create three threads, one for each entity class InternetBankingSystem { public static void main(String [] args ) { Account accountObject = new Account (); Thread t1 = new Thread(new MyThread(accountObject)); Thread t2 = new Thread(new YourThread(accountObject)); Thread t3 = new Thread(new HerThread(accountObject)); t1.start(); t2.start(); t3.start(); // DO some other operation } // end main() } Java entry point Start threads and execute run method of each one Based on Raj Buyya’s slides, “Multithreaded Programming using Java Threads” www.buyya.com

Shared account account (shared object) class MyThread implements Runnable { Account account; public MyThread (Account s) { account = s; } public void run() { account.deposit(); } // end class MyThread class YourThread implements Runnable { public YourThread (Account s) { account.withdraw(); } // end class YourThread class HerThread implements Runnable { public HerThread (Account s) { account.enquire(); } // end class HerThread Shared account account (shared object)

Synchronized Statements Unlike synchronized methods, synchronized statements must specify object that provides intrinsic lock. Uses construct: synchronized ( expression ) { … statements } Evaluate to an object or an array. Used to identify lock. “critical section” Example public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); Only this part synchronized

atomic action An atomic action cannot stop in the middle - it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete. Read/writes can be declared atomic with the volatile keyword, e.g. private volatile int x; Sometimes can be more efficient than synchronized methods.

Wait/notify mechanism Coordinating threads Wait/notify mechanism Sometimes need a thread to stop running and wait for an event before continuing. wait() and notify() methods are methods of class Object. Every object can maintain a list of waiting threads. wait() When a thread calls wait() method of an object, any locks the thread holds are temporarily released and thread added to list of waiting threads for that object and stops running. notify() When another thread calls notify() method on the same object, object wakes up one of the waiting threads and allows it to continue.

Join Sometimes one thread needs to stop and wait for another thread to complete. join() -- waits for a thread to die, i.e. thr1.join() waits for thread thr1 to die. Calling return() from the run method implicitly causes the thread to exit.

Java Example using a monitor

More information http://java.sun.com/docs/books/tutorial/essential/concurrency/