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.

Slides:



Advertisements
Similar presentations
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Advertisements

IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
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.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Chapter 21 – Multithreading
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
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.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
ThreadThread Thread Basics Thread Synchronization Animations.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Multithreading.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Chapter 21 – Multithreading Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 19 Multithreading.
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
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.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Threading Eriq Muhammad Adams J
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Multithreading [Modified]
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
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.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
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)
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.
1 Chapter 19 Multithreading. 2 Objectives F To understand the concept of multithreading and apply it to develop animation (§19.2). F To develop thread.
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.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Threads and Animation Threads Animation.
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.
Parallel Thinking with Java Multithreading. Introduction Algorithms which make use of more than one processor Very hot topic today because all chip manufacturers.
Lec 10 agenda >git fetch origin lab10g; > git checkout -b lab10g origin/lab10g; Format/rules for Week 11 Advanced Topics (all beyond the scope of this.
Chapter 23 Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race.
CSCD 330 Network Programming
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Chapter 22 – Multithreading
Multi Threading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Multithreading Chapter 9.
Chapter 22 – Multithreading
Threads Chate Patanothai.
ITEC324 Principle of CS III
Multithreading.
Multithreading.
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
CSCD 330 Network Programming
Chapter 9 Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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 of other parts of the program The Java Virtual Machine executes each thread in the program for a short amount of time The Java Virtual Machine executes each thread in the program for a short amount of time This gives the impression of parallel execution This gives the impression of parallel execution

Steps to Running a Threads Implement a class that extends the Thread class Implement a class that extends the Thread class Place the code for your task into the run method of your class Place the code for your task into the run method of your class Create an object of your subclass Create an object of your subclass Call the start method of your class to start the thread Call the start method of your class to start the thread When a Thread object is started, the code in its run method is executed in a new thread When a Thread object is started, the code in its run method is executed in a new thread

GreetingThread Outline A program to print a time stamp and "Hello World" once a second for ten seconds A program to print a time stamp and "Hello World" once a second for ten seconds public class GreetingThread extends Thread public class GreetingThread extends Thread {//variables used by the thread action {//variables used by the thread action public void run() { //thread action... } }

Thread Action for GreetingThread Print a time stamp Print a time stamp Print the greeting Print the greeting Wait a second Wait a second

GreetingThread We can get the date and time by constructing Date object Date now = new Date(); We can get the date and time by constructing Date object Date now = new Date(); To wait a second, use the sleep method of the Thread class sleep(milliseconds) To wait a second, use the sleep method of the Thread class sleep(milliseconds) A sleeping thread can generate an InterruptedException A sleeping thread can generate an InterruptedException o Catch the exception o Terminate the thread

GreetingThread run method public run() {try{ //thread action } catch (InterruptedException exception) { //cleanup, if necessary }}

File GreetingThread.java 01: import java.util.Date; 02: 03: /** 04: A thread that repeatedly prints a greeting. 05: */ 06: public class GreetingThread extends Thread 07: { // constants private static final int REPETITIONS = 10; private static final int REPETITIONS = 10; private static final int DELAY = 1000; private static final int DELAY = 1000; //instance variable //instance variable private String greeting; private String greeting; 08: /** 09: Constructor. aGreeting the greating to display 11: */ 12: public GreetingThread(String aGreeting) 13: { 14: greeting = aGreeting; 15: } 16:

17: public void run() 18: { 19: try 20: { 21: for (int i = 1; i <= REPETITIONS; i++) 22: { 23: Date now = new Date(); 24: System.out.println(now + " " + greeting); 25: sleep(DELAY); 26: } 27: } 28: catch (InterruptedException exception) 29: { 30: } 31: } 32:}

To Start the Thread Construct an object of your thread class GreetingThread t = new GreetingThread("Hello World"); Construct an object of your thread class GreetingThread t = new GreetingThread("Hello World"); Call the start method that belongs to Thread Call the start method that belongs to Thread t.start(); t.start();

File GreetingThreadTest.java 01: import java.util.Date; 02: 03: /** 04: This program tests the greeting thread by running two 05: threads in parallel. 06: */ 07: public class GreetingThreadTest 08: { 09: public static void main(String[] args) 10: { 11: GreetingThread t1 = new GreetingThread("Hello, World!"); 12: GreetingThread t2 = new GreetingThread("Goodbye, World!"); 13: 14: t1.start(); 15: t2.start(); 16: } 17: }

Thread Scheduler The thread scheduler runs each thread for a short amount of time called a time slice The thread scheduler runs each thread for a short amount of time called a time slice Then the scheduler picks another thread from those that are runnable Then the scheduler picks another thread from those that are runnable A thread is runnable if it is not asleep or blocked in some way A thread is runnable if it is not asleep or blocked in some way There is no guarantee about the order in which threads are executed There is no guarantee about the order in which threads are executed

Terminating Threads A thread terminates when its run method returns A thread terminates when its run method returns Do not terminate a thread using the deprecated stop method Do not terminate a thread using the deprecated stop method Instead, notify a thread that it should terminate Instead, notify a thread that it should terminatet.interrupt();

Terminating Threads A thread's run method should check occasionally whether it has been interrupted A thread's run method should check occasionally whether it has been interrupted o Use the isInterrupted method o An interrupted thread should release resources, clean up, and exit The sleep method throws an InterruptedException when a sleeping thread is interrupted The sleep method throws an InterruptedException when a sleeping thread is interrupted o Catch the exception o Terminate the thread

Terminating a Thread public void run( {try{ for (int = 1; i <= REPETITIONS && !isInterrupted(); i++) { //do the work } } catch (InterruptedException exception) catch (InterruptedException exception) { } { } //cleanup //cleanup}

Corrupting Data with Unsynchronized Threads When threads share a common object, they can conflict with each other. When threads share a common object, they can conflict with each other. In this example, a DepositThread and a WithdrawThread both manipulate a single BankAccount In this example, a DepositThread and a WithdrawThread both manipulate a single BankAccount

run Method of DepositThread public void run() { try try { for (int i = 1; i <= REPETITIONS && !isInterrupted(); i++) for (int i = 1; i <= REPETITIONS && !isInterrupted(); i++) { account.deposit(amount); account.deposit(amount); sleep(DELAY); sleep(DELAY); } } catch (InterruptedException exception) catch (InterruptedException exception) { } }

Sample Application Create a BankAccount object Create a BankAccount object Create a DepositThread t0 to deposit $100 into the account for 10 iterations Create a DepositThread t0 to deposit $100 into the account for 10 iterations Create a WithdrawThread t1 to withdraw $100 from the account for 10 iterations Create a WithdrawThread t1 to withdraw $100 from the account for 10 iterations The result should be zero, but sometimes it is not The result should be zero, but sometimes it is not

Race condition Occurs if the effect of multiple threads on shared data depends on the order in which the threads are scheduled Occurs if the effect of multiple threads on shared data depends on the order in which the threads are scheduled It is possible for a thread to reach the end of its time slice in the middle of a statement. It is possible for a thread to reach the end of its time slice in the middle of a statement. It may evaluate the right-hand side of an equation but not be able to store the result until its next turn. It may evaluate the right-hand side of an equation but not be able to store the result until its next turn.

Solving the Race Condition Problem A thread must be able to lock an object temporarily A thread must be able to lock an object temporarily When a thread has the object locked, no other thread can modify the state of the object. When a thread has the object locked, no other thread can modify the state of the object. In Java, use synchronized methods to do this In Java, use synchronized methods to do this Tag all methods that contain thread-sensitive code with the keyword synchronized Tag all methods that contain thread-sensitive code with the keyword synchronized

Synchronized Methods public class BankAccount { public synchronized void deposit(double amount) public synchronized void deposit(double amount) { } public synchronized void withdraw(double amount) public synchronized void withdraw(double amount) { } }

Synchronized Methods By declaring both the deposit and withdraw methods to be synchronized By declaring both the deposit and withdraw methods to be synchronized oOur program will run correctly oOnly one thread at a time can execute either method on a given object oWhen a thread starts one of the methods, it is guaranteed to execute the method to completion before another thread can execute a synchronized method on the same object.

Synchronized Methods By executing a synchronized method: By executing a synchronized method: oThe thread acquires the object lock. oNo other thread can acquire the lock. oNo other thread can modify the state of the object until the first thread is finished

Deadlock A deadlock occurs if no thread can proceed because each thread is waiting for another to do some work first A deadlock occurs if no thread can proceed because each thread is waiting for another to do some work first BankAccount example BankAccount example public synchronized void withdraw(double amount) public synchronized void withdraw(double amount) { while (balance < amount) while (balance < amount) //wait for balance to grow //wait for balance to grow }

Deadlock The method can lead to deadlock The method can lead to deadlock The thread sleeps to wait for balance to grow, but it still has the lock The thread sleeps to wait for balance to grow, but it still has the lock No other thread can execute the synchronized deposit method No other thread can execute the synchronized deposit method If a thread tries to call deposit, it is blocked until the withdraw method exits If a thread tries to call deposit, it is blocked until the withdraw method exits withdraw method can't exit until it has funds available withdraw method can't exit until it has funds available DEADLOCK DEADLOCK

Avoiding Deadlock The wait method temporarily releases the object lock and deactivates the thread The wait method temporarily releases the object lock and deactivates the thread

withdraw Method to Avoid Deadlock public synchronized void withdraw(double amount) throws InterruptedException throws InterruptedException{ while (balance < amount) while (balance < amount) wait(); wait();}

Wait and NotifyAll A thread that calls wait is in a blocked state A thread that calls wait is in a blocked state It will not be activated by the thread scheduler until it is unblocked It will not be activated by the thread scheduler until it is unblocked It is unblocked when another thread calls notifyAll It is unblocked when another thread calls notifyAll When a thread calls notifyAll, all threads waiting on the object are unblocked When a thread calls notifyAll, all threads waiting on the object are unblocked Only the thread that has the lock can call notifyAll Only the thread that has the lock can call notifyAll

File BankAccountThreadTest.java Using synchronized methods 01: import java.util.Random; 02: 03: /** 04: This program runs four threads that deposit and withdraw 05: money from the same bank account. 06: */ 07: public class BankAccountThreadTest 08: { 09: public static void main(String[] args) 10: {

11: BankAccount account = new BankAccount(); 12: 13: DepositThread t0 = new DepositThread(account, 100); 14: WithdrawThread t1 = new WithdrawThread(account, 100); 15: DepositThread t2 = new DepositThread(account, 100); 16: WithdrawThread t3 = new WithdrawThread(account, 100); 17: 18: t0.start(); 19: t1.start(); 20: t2.start(); 21: t3.start(); 22: } 23: }

File BankAccount.java 01: /** 02: A bank account has a balance that can be changed by 03: deposits and withdrawals. 04: */ 05: public class BankAccount 06: { 07: /** 08: Constructs a bank account with a zero balance 09: */ 10: public BankAccount() 11: { 12: balance = 0; 13: } 14: 15: /** 16: Deposits money into the bank account. amount the amount to deposit

18: */ 19: public synchronized void deposit(double amount) 20: { 21: System.out.print("Depositing " + amount); 22: double newBalance = balance + amount; 23: System.out.println(", new balance is " + newBalance); 24: balance = newBalance; 25: notifyAll(); 26: } 27: 28: /** 29: Withdraws money from the bank account. amount the amount to withdraw 31: */ 32: public synchronized void withdraw(double amount) 33: throws InterruptedException 34: { 35: while (balance < amount) 36: wait(); 37: System.out.print("Withdrawing " + amount);

38: double newBalance = balance - amount; 39: System.out.println(", new balance is " + newBalance); 40: balance = newBalance; 41: } 42: 43: /** 44: Gets the current balance of the bank account. the current balance 46: */ 47: public double getBalance() 48: { 49: return balance; 50: } 51: 52: private double balance; 53: }

Animation Animation shows different objects moving or changing as time progresses Animation shows different objects moving or changing as time progresses Thread programming is useful in animation Thread programming is useful in animation An algorithm animation helps visualize the steps in the algorithm An algorithm animation helps visualize the steps in the algorithm

Algorithm Animation Runs in a separate thread that periodically updates an image of the current state of the algorithmRuns in a separate thread that periodically updates an image of the current state of the algorithm It then pauses so the user can see the changeIt then pauses so the user can see the change After a short time the algorithm thread wakes up and runs to the next point of interestAfter a short time the algorithm thread wakes up and runs to the next point of interest It updates the image again and pauses againIt updates the image again and pauses again

Applet to Provide User Interface Start the animation with a mousePressed event If an animation is already running, interrupt the thread to terminate it Start the animation with a mousePressed event If an animation is already running, interrupt the thread to terminate it public class SelectionSortApplet extends Applet { private Thread animation public SelectionSortApplet() public SelectionSortApplet() { class MousePressListener extends MouseAdapter class MousePressListener extends MouseAdapter { public void mousePressed(MouseEvent event) public void mousePressed(MouseEvent event) { if (animation != null && animation.isAlive()) if (animation != null && animation.isAlive()) animation.interrupt(); animation.interrupt(); startAnimation(); startAnimation(); }

} MouseListener listener = new MousePressListener(); MouseListener listener = new MousePressListener(); addMouseListener(listener); addMouseListener(listener); animation = null; animation = null; } }