© 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.

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.
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.
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?
CS 11 java track: lecture 7 This week: Web tutorial:
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
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
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.
28-Jun-15 Producer-Consumer An example of using Threads.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Threads Written by Amir Kirsh, Dr. Yaron Kanza. Edited by Liron Blecher.
More Multithreaded Programming in Java David Meredith Aalborg University.
Multithreading.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 19 th, 2010 The University of Georgia.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Threads some important concepts Simon Lynch
1 Java Threads and Synchronization Review Modified from slides taken from
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.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Practice Session 8 Blocking queues Producers-Consumers pattern Semaphore Futures and Callables Advanced Thread Synchronization Methods CountDownLatch Thread.
Threading Eriq Muhammad Adams J
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
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.
Multithreading in JAVA
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
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.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Module 6: Process Synchronization Codes.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
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.
Multithreading and Garbage Collection Session 16.
1 Java Programming Java Programming II Concurrent Programming: Threads ( II)
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
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.
Java Thread Programming
Threads in Java Two ways to start a thread
Thread Pools (Worker Queues) cs
Multi Threading.
Multithreading.
Java Programming Language
Java Concurrency.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Java Concurrency.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Threads in Java James Brucker.
Multithreading in java.
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

© 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 Be able to create Java multithreaded applications

Agenda Threads Overview Creating threads in Java Synchronization wait() and notify() Thread Pools Exercise

4 Threads Overview – Threads allow the program to run tasks in parallel – In many cases threads need to be synchronized, that is, be kept not to handle the same data in memory concurrently – There are cases in which a thread needs to wait for another thread before proceeding Never use thread-per-session – this is a wrong and un-scaled architecture – use instead Thread Pools

Agenda Threads Overview Creating threads in Java Synchronization wait() and notify() Thread Pools Exercise

6 Threads in Java The operation we want to be threaded: public class PrintNumbers { static public void printNumbers() { for(int i=0; i<1000; i++) { System.out.println( Thread.currentThread().getId() + ": " + i); }

7 Threads in Java Option 1 – extending class Thread: public class Thread1 extends Thread public void run() { System.out.println("Thread1 ThreadId: " + Thread.currentThread().getId()); // do our thing PrintNumbers. printNumbers(); // the super doesn't anything, // but just for the courtesy and good practice super.run(); }

8 Threads in Java Option 1 – extending class Thread (cont’): static public void main(String[] args) { System.out.println("Main ThreadId: " + Thread.currentThread().getId()); for(int i=0; i<3; i++) { new Thread1().start(); // don't call run! // (if you want a separate thread) } printNumbers(); }

9 Threads in Java Option 2 – implementing Runnable: public class Thread2 implements Runnable public void run() { System.out.println("Thread2 ThreadId: " + Thread.currentThread().getId()); // do our thing PrintNumbers. printNumbers(); }

10 Threads in Java Option 2 – implementing Runnable (cont’): static public void main(String[] args) { System.out.println("Main ThreadId: " + Thread.currentThread().getId()); for(int i=0; i<3; i++) { new Thread(new Thread2()).start(); // again, don't call run! // (if you want a separate thread) } printNumbers(); }

11 Threads in Java Option 3 – implementing Runnable as Anonymous: static public void main(String[] args) { System.out.println("Main ThreadId: " + Thread.currentThread().getId()); new Thread(new Runnable() public void run() { System.out.println("Thread3 ThreadId: " + Thread.currentThread().getId()); // do our thing printNumbers(); } }).start(); // don't call run!... printNumbers(); }

Agenda Threads Overview Creating threads in Java Synchronization wait() and notify() Thread Pools Exercise

13 Synchronization Synchronization of threads is needed for in order to control threads coordination, mainly in order to prevent simultaneous operations on data For simple synchronization Java provides the synchronized keyword For more sophisticated locking mechanisms, starting from Java 5, the package java.concurrent.locks provides additional locking options, see: locks/package-summary.html locks/package-summary.html

14 public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } } Synchronization Example 1 – synchronizing methods: The synchronized keyword on a method means that if this is already locked anywhere (on this method or elsewhere) by another thread, we need to wait till this is unlocked before entering the method Reentrant is allowed

15 public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); } Synchronization Example 2 – synchronizing blocks: When synchronizing a block, key for the locking should be supplied (usually would be this) The advantage of not synchronizing the entire method is efficiency

16 public class TwoCounters { private long c1 = 0, c2 = 0; private Object lock1 = new Object(); private Object lock2 = new Object(); public void inc1() { synchronized(lock1) { c1++; } public void inc2() { synchronized(lock2) { c2++; } Synchronization Example 3 – synchronizing using different locks: You must be absolutely sure that there is no tie between c1 and c2

17 public class Screen { private static Screen theScreen; private Screen(){…} // private c’tor public static synchronized getScreen() { if(theScreen == null) { theScreen = new Screen(); } return theScreen; } Synchronization Example 4 – synchronizing static methods: This is a Singleton example It is not the most efficient way to implement Singleton in Java

18 Synchronization Example 4 – synchronizing static methods … Having a static method be synchronized means that ALL objects of this type are locked on the method and can get in one thread at a time. The lock is the Class object representing this class. The performance penalty might be sometimes too high – needs careful attention!

19 public class Screen { private static Screen theScreen = new Screen(); private Screen(){…} // private c’tor public static getScreen() { return theScreen; } Synchronization Example 4’ – a better singleton: No synchronization

Agenda Threads Overview Creating threads in Java Synchronization wait() and notify() Thread Pools Exercise

21 wait(), notify(), notifyAll() This is an optional topic We may skip it…skip it

22 wait(), notify(), notifyAll() wait() and notify() allows a thread to wait for an event A call to notifyAll() allows all threads that are on wait() with the same lock to be released A call to notify() allows one arbitrary thread that is on a wait() with the same lock to be released Read: (a) essential/concurrency/guardmeth.html (b) java/lang/Object.html#wait() essential/concurrency/guardmeth.htmlhttp://java.sun.com/javase/6/docs/api/ java/lang/Object.html#wait() Instead of “busy wait” or sleep loop!

23 public class Drop { // Message sent from producer to consumer private String message; // A flag, True if consumer should wait for // producer to send message, False if producer // should wait for consumer to retrieve message private boolean empty = true;... wait(), notify(), notifyAll() Example (from ) : Flag must be used, never count only on the notify

24 public class Drop {... public synchronized String take() { // Wait until message is available while (empty) { // we do nothing on InterruptedException // since the while condition is checked anyhow try { wait(); } catch (InterruptedException e) {} } // Toggle status and notify on the status change empty = true; notifyAll(); return message; }... } wait(), notify(), notifyAll() Example (cont’) Must be in synchronized context

25 public class Drop {... public synchronized void put(String message) { // Wait until message has been retrieved while (!empty) { // we do nothing on InterruptedException // since the while condition is checked anyhow try { wait(); } catch (InterruptedException e) {} } // Toggle status, store message and notify consumer empty = false; this.message = message; notifyAll(); }... } wait(), notify(), notifyAll() Example (cont’) Must be in synchronized context

Agenda Threads Overview Creating threads in Java Synchronization wait() and notify() Thread Pools Exercise

27 Thread Pools Prevernt the thread-per-session pitfall! Class ThreadPoolExecutor: ThreadPoolExecutor.html ThreadPoolExecutor.html

Agenda Threads Overview Creating threads in Java Synchronization wait() and notify() Thread Pools Exercise

29 Exercise Implement a multithreaded application performing X sessions of the PrintNumbers.printNumbers task, (presented at the beginning of this lesson) – with a Thread Pool of Y threads X and Y should be retrieved from the command-line

30 That concludes this chapter amirk at mta ac il