ThreadThread Thread Basics Thread Synchronization Animations.

Slides:



Advertisements
Similar presentations
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Advertisements

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.
1 Race Conditions When threads share access to a common object/data, they can conflict with each other and mess up the consistency of the object/data.
Multithreading Horstmann ch.9. Multithreading Threads Thread states Thread interruption Race condition Lock Built-in lock java.util.concurrent library.
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.
Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee.
Multithreading. RHS – SWC 2 What is a thread Inside a single process, multiple threads can be executing concurrently A thread is the execution of (part.
1Quiz Modify HelloWorld2.java; –Remove (or comment out) the following 4 lines: Thread thread1 = new Thread(runnable1); Thread thread2 = new Thread(runnable2);
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Multithreading. 2 Threads Program units that execute independently; multiple threads run “simultaneously” Virtual machine executes each thread for short.
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.
Definitions Process – An executing program
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.
Multithreading.
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.
1 Java Threads and Synchronization Review Modified from slides taken from
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Java threads: Introduction
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
111 © 2002, Cisco Systems, Inc. All rights reserved.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Next week (July 21) –No class –No office hour. Problem Multiple tasks for computer –Draw & display images on screen –Check keyboard & mouse input –Send.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
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.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
CS 151: Object-Oriented Design November 21 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
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.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
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.
CMSC 330: Organization of Programming Languages Threads.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
CS 152: Programming Language Paradigms April 30 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
CS 151: Object-Oriented Design November 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
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.
Multithreading. DCS – SWC 2 What is a thread Inside a single process, multiple threads can be executing concurrently A thread is the execution of (part.
Distributed and Parallel Processing George Wells.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Multi Threading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Java Concurrency.
Multithreading Chapter 9.
Threads Chate Patanothai.
ITEC324 Principle of CS III
Java Concurrency.
Condition Variables and Producer/Consumer
Multithreading.
Condition Variables and Producer/Consumer
Java Based Techhnology
برنامه‌نویسی چندنخی Multi-Thread Programming
Threads and Multithreading
Chapter 9 Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

ThreadThread Thread Basics Thread Synchronization Animations

Thread Thread: program unit that is executed independently Multiple threads run simultaneously Virtual machine executes each thread for short time slice Thread scheduler activates, deactivates threads Illusion of threads running in parallel Multiprocessor computers: threads actually run in parallel

Running Threads Define class that implements Runnable Runnable has one method void run() Place thread action into run method Construct object of runnable class Construct thread from that object Start thread public class MyRunnable implements Runnable { public void run() { thread action } }... Runnable r = new MyRunnable(); Thread t = new Thread(t); t.start();

Run two threads in parallel Ch9/greeting/GreetingProducer.java Ch9/greeting/ThreadTester.java

Note: output not exactly interleaved 1: Hello, World! 1: Goodbye, World! 2: Hello, World! 2: Goodbye, World! 3: Hello, World! 3: Goodbye, World! 4: Hello, World! 4: Goodbye, World! 5: Hello, World! 5: Goodbye, World! 6: Hello, World! 6: Goodbye, World! 7: Hello, World! 7: Goodbye, World! 8: Goodbye, World! 8: Hello, World! 9: Goodbye, World! 9: Hello, World! 10: Goodbye, World! 10: Hello, World!

Thread States Blocked Thread State Reasons for blocked state: Sleeping Waiting for I/O Waiting to acquire lock (later) Waiting for condition (later) Unblocks only if reason for block goes away

Scheduling Threads Scheduler activates new thread if –a thread has completed its time slice –a thread has blocked itself –a thread with higher priority has become runnable Scheduler determines new thread to run –looks only at runnable threads –picks one with max priority

Terminating Threads Thread terminates when run exits Sometimes necessary to terminate running thread Don't use deprecated stop method Interrupt thread by calling interrupt Calling t.interrupt() doesn't actually interrupt t; just sets a flag Interrupted thread must sense interruption and exit its run method Interrupted thread has chance to clean up

Extends Thread public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); }

Thread methods thread.start ( ); b = thread.isAlive ( ); thread.interrupt ( ); b = thread.isInterrupted ( ); Static Thread Methods curr = Thread.currentThread ( ); b = Thread.interrupted ( ); Thread.sleep (millis); Thread.sleep (millis, nanos);

Sensing Interruptions public class MyRunnable implements Runnable { public void run() { try { while (...) { do work Thread.sleep(...); } } catch (InterruptedException e) {} clean up } }

Thread Synchronization Producer Thread int i = 1; while (i <= greetingCount) { if (!queue.isFull()) { queue.add(i + ": " + greeting); i++; } Thread.sleep((int) (Math.random() * DELAY)); } Consumer Thread int i = 1; while (i <= greetingCount) { if (!queue.isEmpty()) { Object greeting = queue.remove(); System.out.println(greeting); i++; } Thread.sleep((int) (Math.random() * DELAY)); }

Thread Synchronization Expected Program Output 1: Hello, World! 1: Goodbye, World! 2: Hello, World! 3: Hello, World!... 99: Goodbye, World! 100: Goodbye, World!

Thread Synchronization Why is Output Corrupted? Sometimes program gets stuck and doesn't complete Can see problem better when turning debugging on queue.setDebug(true); Ch9/queue1/ThreadTester.java Ch9/queue1/Producer.java Ch9/queue1/Consumer.java Ch9/queue1/BoundedQueue.java

Race Condition A race condition occurs if the effect of multiple threads on shared data depends on the order in which the threads are scheduled Illusion of correctness !

Locks Thread can acquire lock When another thread tries to acquire same lock, it blocks When first thread releases lock, other thread is unblocked and tries again Two kinds of locks –Objects of class implementing java.util.concurrent.Lock interface type, usually ReentrantLock –Locks that are built into every Java object

Reentrant Locks (java 5 interface) aLock = new ReentrantLock();... aLock.lock(); try { protected code } finally { aLock.unlock(); }

Deadlocks if (!queue.isFull()) queue.add(...); can still be interrupted Must move test inside add method public void add(E newValue) { queueLock.lock(); try { while (queue is full) wait for more space... } finally { qeueLock.unlock(); } } Problem: nobody else can call remove...if no thread can proceed because waiting waiting for onother...

Avoiding Deadlocks Use condiiton object to manage "space available" condition private Lock queueLock = new ReentrantLock(); private Condition spaceAvailableCondition = queueLock.newCondition(); Call await when condition is not fulfilled: public void add(E newValue) {... while (size == elements.length) spaceAvailableCondition.await();... }

Object Locks Each object has a lock Calling a synchronized method acquires lock of implicit parameter Leaving the synchronized method releases lock Easier than explicit Lock objects public class BoundedQueue { public synchronized void add(E newValue) {... } public synchronized E remove() {... }... }

Object Locks Object.wait blocks current thread and adds it to wait set Object.notifyAll unblocks waiting threads public synchronized void add(E newValue) throws InterruptedException { while (size == elements.length) wait(); elements[tail] = anObject;... notifyAll(); // notifies threads waiting to remove elements } Ch9/queue3/BoundedQueue.java