Threads  A thread is single sequence of executable statements within a program  eg.) a typical application is a thread, with the flow of control beginning.

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Ch. 7 Process Synchronization (1/2) I Background F Producer - Consumer process :  Compiler, Assembler, Loader, · · · · · · F Bounded buffer.
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
1 Lecture 18 Further Threading Overview  Case Study: Cooperating Threads  Producer/ Consumer model threads  Waiting for Synchronized Data  Busy Waiting.
JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli | Ralph Walde Trinity College Hartford, CT presentation slides for published by Prentice.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Multithreading The objectives of this chapter are:
Object-Oriented Software Engineering Concurrent Programming.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
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.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java, Java, Java Object Oriented Problem Solving Chapter 13: Threads and Concurrent Programming.
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.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Internet Software Development More stuff on Threads Paul Krause.
1 Java Threads Instructor: Mainak Chaudhuri
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
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.
1 Web Based Programming Section 8 James King 12 August 2003.
Concurrent Programming and Threads Threads Blocking a User Interface.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
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
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.
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
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.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
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.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
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.
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
Multithreading The objectives of this chapter are:
CSCD 330 Network Programming
Doing Several Things at Once
Multithreading / Concurrency
Chapter 13: Multithreading
Multi Threading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Multithreading Chapter 9.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Condition Variables and Producer/Consumer
Multithreading.
Condition Variables and Producer/Consumer
Multithreading 2 Lec 24.
Multithreading.
Multithreaded Programming
Computer Science 2 06A-Java Multithreading
CSCD 330 Network Programming
Lecture 19 Threads CSE /6/2019.
Multithreading The objectives of this chapter are:
Software Engineering and Architecture
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads  A thread is single sequence of executable statements within a program  eg.) a typical application is a thread, with the flow of control beginning with the first statement in the main method the flow of control beginning with the first statement in the main method Although there are control structures and method invocations involved, you can trace the sequential flow of execution from one statement to the next. Although there are control structures and method invocations involved, you can trace the sequential flow of execution from one statement to the next.

Threads  Java supports concurrent processes (multi-thread programs)  Single CPU handles this by alternating its resources between threads (managed by JVM and operating system)  The JVM is itself a multithreaded program (the garbage collector is a thread, which reclaims memory taken up by objects that are not being used)

Steps to Writing a Thread Class  Implement a class that extends the Thread class  You will inherit a start() method and a run() method  Override the run() method and place the code for your task into the run() method of your class  A code in your run() method will be executed in a new Thread once an object of this type has been instantiated, and the start() method has been called.  Do NOT call the run method directly, this will not start a new thread……

Example: public class NumberThread extends Thread { private int num; private int num; private int total; private int total; public NumberThread(int n, int ttl) { public NumberThread(int n, int ttl) { num = n; num = n; total = ttl; total = ttl; } //this code will run in it’s own thread //this code will run in it’s own thread //when ‘started’ //when ‘started’ public void run(){ public void run(){ for (int count = 0; count < total; count++) System.out.println(num); System.out.println(num);} }

public class Numbers { public static void main (String[] args){ public static void main (String[] args){ NumberThread numOne, numTwo, numThree; NumberThread numOne, numTwo, numThree; numOne = new NumberThread(11,10); numOne = new NumberThread(11,10); numTwo = new NumberThread(22,10); numTwo = new NumberThread(22,10); numThree = new NumberThread(33,10); numThree = new NumberThread(33,10); numOne.start(); numOne.start(); numTwo.start(); numTwo.start(); numThree.start(); numThree.start(); }}

You can convert any class to a Thread by having that class implement the Runnable interface…and then using the Thread constructor: Thread (Runnable r) If our NumberThread class implemented Runnable, If our NumberThread class implemented Runnable, we would start our Thread in this manner: we would start our Thread in this manner: NumberThread num1 = new NumberThread(20,15); NumberThread num1 = new NumberThread(20,15); Thread th1 = new Thread (num1); Thread th1 = new Thread (num1); th1.start(); th1.start();

Stopping a Thread To stop a thread, you must interrupt it. To stop a thread, you must interrupt it. public static void main (String[] args){ NumberThread numOne, numTwo, numThree; NumberThread numOne, numTwo, numThree; numOne = new NumberThread(11,10); numOne = new NumberThread(11,10); numTwo = new NumberThread(22,10); numTwo = new NumberThread(22,10); numThree = new NumberThread(33,10); numThree = new NumberThread(33,10); numOne.start(); numOne.start(); numTwo.start(); numTwo.start(); numThree.start(); numThree.start(); ……. ……. numTwo.interrupt(); numTwo.interrupt(); }

Thread code can check if it has been interrupted: public class NumberThread extends Thread { private int num; private int num; private int total; private int total; public NumberThread(int n, int ttl) { public NumberThread(int n, int ttl) { num = n; num = n; total = ttl; total = ttl; } public void run(){ public void run(){ int count = 0; int count = 0; while (count < total & !isInterrupted()) System.out.println(num); System.out.println(num); count++; count++;} if (isInterrupted() ) //clean up //clean up }

Thread Behavior The Thread.sleep() method can halt a running thread for a given number of milliseconds, allowing other threads to run The Thread.sleep() method can halt a running thread for a given number of milliseconds, allowing other threads to run The Thread.yield() method halts a running thread and allows that thread to be preempted by another, if the CPU so chooses The Thread.yield() method halts a running thread and allows that thread to be preempted by another, if the CPU so chooses The Thread.sleep() method throws an InterruptedException if the thread is interrupted while it is sleeping (InterruptedException is a checked exception) The Thread.sleep() method throws an InterruptedException if the thread is interrupted while it is sleeping (InterruptedException is a checked exception) Signatures for sleep method Signatures for sleep method static void Thread.sleep(long milli) static void Thread.sleep(long milli) static void Thread.sleep(long milli, long nano) static void Thread.sleep(long milli, long nano)

Sleep call must be used in a try block… public class NumberThread extends Thread{ ….. ….. public void run(){ public void run(){try{ for (int count = 0; count < total; count++) for (int count = 0; count < total; count++) System.out.println(num); System.out.println(num); Thread.sleep((long) Math.random() *1000); Thread.sleep((long) Math.random() *1000); } catch (InterruptedException e) { catch (InterruptedException e) { any code needed to clean up loose ends any code needed to clean up loose ends }}

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 queued to be ready, or runnable. A thread is runnable if it is not asleep or blocked in some way Then the scheduler picks another thread from those that are queued to be ready, or runnable. A thread is runnable if it is not asleep or blocked in some way

Let’s look at a larger application of threads.. Suppose a psychologist want to be able to conduct an experiment to measure user response to a visual cue. An application is needed which can draw black dots a random positions on the screen, and, after a random time interval, begins drawing red dots. The test begins when the patient clicks on a Draw button. As soon as the red dots appear, the patient is to click on a Clear button, which clears the drawing area. The program must provide how many red dots have appeared before the user clicked in order to measure the patient reaction time.

An object of type DotPanel draws dots on a panel when it’s draw method is called. An object of type DotPanel draws dots on a panel when it’s draw method is called. An object of type DotPanel clears the panel when it’s clear method is called. The Stimuli class uses the DotPanel class to draw dots on a panel. Run Stimuli.java with DotPanel.java. Run Stimuli.java with DotPanel.java. What happens when the Clear button is pressed while the dots are being drawn?? What happens when the Clear button is pressed while the dots are being drawn??

That’s right. Nothing happens. That is because the CPU is busy executing that for loop, and there is no chance for it to see a user action. We can fix this by: 1.) executing the drawing in a separate thread 2.) allowing that new thread to sleep occasionally, so the CPU will recognize user intervention Take a look at DotPanel2.java and Simuli2.javaDotPanel2.java

Thread Synchronization Threads are asynchronous.. That is, there is no guarantee about the order in which threads are executed, or when they might get pre-empted. Threads are asynchronous.. That is, there is no guarantee about the order in which threads are executed, or when they might get pre-empted. In many cases it is essential to be able to control the thread execution to some extent -- ie.) synchronize them. In many cases it is essential to be able to control the thread execution to some extent -- ie.) synchronize them.

Let’s code a small simulation of a bakery, which uses a Take-A- Number machine to manage a waiting line. Customers will take a number when they arrive, and the clerk announces who’s next by looking at the device. All this is happening at the same time. Many cooperative applications are based on the producer/consumer model where two threads cooperate at producing and consuming a particular resource or piece of data. The producer thread creates some result or message, and the consumer result uses that result or message. In our simulation, the customer is the producer, and the clerk is the consumer. The work cooperatively -- the customer generating a range of numbers waiting to be served, while the clerk uses these numbers.

We will need 4 classes: the Bakery class (our application) the TakeANumber class (an object of this type is shared by customers and the clerk) the Customer class the Clerk class As mentioned before, the the customers and clerk work simultaneously, and so these objects should each run in their own thread.

This class must keep track of the next number given AND which customer is to be served next. It is essential that only one customer be able to take a number at a time. As many Customer objects will have access to this object, how do we insure that only one take a number at a time?? class TakeANumber { private int next = 0; private int serving = 0; public int getNum() { next = next + 1; return next; } public int nextCustomer () { ++serving; return serving; } synchronized When a synchronized method is called, a lock is placed on that object. While the lock is in place, no other synchronized method can run in that object.

Customer thread should model the taking a number from the TakeANumber gadget. ( To keep this program simple we will just assume that after taking a number the customer prints it out.) public class Customer extends Thread{ private int id; //to distinguish one customer from another private static int number = 0; //initial customer id number private TakeANumber takenum; //store reference to machine public Customer (TakeANumber takeRef){ id = number; number = number + 1; takenum = takeRef; } public void run(){ try{ sleep( (int)(Math.random() * 1000)) ; //customer walks to machine System.out.println((“Customer “+ id + “takes ticket “+takenum.getNum()); } catch ( InterruptedException e) {} }

The Clerk thread must simulate the behavior of serving the next customer. This thread will repeatedly get the nextCustomer and serve that customer. ( for simplicity we will print a message of who is being served) public class Clerk extends Thread { private TakeANumber takeref; public Clerk (TakeANumber gadget) { takeref = gadget; } public void run() { while(true && !isInterrupted() ){ try{ sleep ( (int) (Math.random() * 50)); System.out.println(“Clerk serving” + takeref.nextCustomer()); } catch (InterruptedException e) { } }

public class Bakery { public static void main (String [] args) { System.out.println(“Starting simulation”); TakeANumber machine = new TakeANumber(); Clerk clerk = new Clerk(machine); clerk.start(); for (int i = 1; i < = 5; i++){ Customer cust = new Customer(machine); cust.start(); }

Let’s run this…………………. What happens??? The clerk is serving non-existent customers!!

How can we fix this?? The clerk is needs to check IF there are customers waiting before getting the next customer. The clerk thread is getting a lot more attention than the customer. Let’s add a customerWaiting() method to the machine, which can correspond to the clerk looking to see if there are other customers..

public class Clerk extends Thread { private TakeANumber takeref; public Clerk (TakeANumber gadget) { takeref = gadget; } public void run() { while(true){ try{ sleep ( (int) (Math.random() * 50)); if (takeref.customerWaiting() ) System.out.println(“Clerk serving” + takeref.nextCustomer()); } catch (InterruptedException e) { break; } } Let’s see if this helps…………

What happened?????????? Maybe it worked fine. MAYBE it didn’t. It is is possible that a thread got pre-empted while executing: System.out.println( “Customer “ + id + “takes ticket “ + takeref.getNum() ): in which case a customer being served is ‘bumped’ by another. We have forgotten that we are writing asynchronous code. This is a CRITICAL SECTION of our application, and should not be interrupted when executing. We can use synchronized methods to help..

class TakeANumber { private int next = 0; private int serving = 0; public synchronized int getNum(int id) { next = next + 1; System.out.println(“Customer “ + id + “ takes ticket “ + next); return next; } public synchronized int nextCustomer () { ++serving; System.out.println(“Clerk serving “ + serving); return serving; } public boolean customerWaiting() { return next > serving; } Let’s put the I/O functionality in the machine, and have it report what it does !!

One last modification ………….. The Clerk run method uses a busy waiting algorithm, which is a terrible waste of CPU time!! It would be better if the Clerk thread waited until there was a customer, without using CPU time !! Thread class methods will help: wait() - puts a thread into waiting state notify() - takes a thread out of waiting and places it back into the waiting queue

If the clerk calls nextCustomer(), and there is NO customer waiting, then the clerk can wait. public class TakeANumber { private int next = 0; private int serving = 0; public synchronized int nextCustomer () { try{ while( next <=serving) wait(); //thread deactivated, object lock released } catch (InterruptedException e){} finally{ ++serving; System.out.println(“Clerk serving “ + serving); return serving; } } //How will the Clerk thread by notified?? public synchronized int getNum(int id) { next = next + 1; System.out.println(“# “+ id +“ takes ticket “+ next); notify(); //clerk waiting is activated return next; }