What is a ‘ thread ’ ? Free Online Dictionary of Computing (FOLDOC) Sharing a single CPU between multiple tasks (or "threads") in a way designed to minimize.

Slides:



Advertisements
Similar presentations
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Advertisements

2015/5/8Institute of Computer Software Nanjing University Concurrent Objects.
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
Multithreading.
Java Programming: Advanced Topics
CGS 3763 Operating Systems Concepts Spring 2013 Dan C. Marinescu Office: HEC 304 Office hours: M-Wd 11: :30 AM.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Inter-Thread communication State dependency: Guarded Methods.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
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.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
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.
1 Concurrency Architecture Types Tasks Synchronization –Semaphores –Monitors –Message Passing Concurrency in Ada Java Threads.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Threads.
1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
1 Introduction to Threads Computers can perform many tasks concurrently – download a file, print a file, receive , etc. Sequential languages such.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 18 Advanced Java Concepts Threads and Multithreading.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Java Thread and Memory Model
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.
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.
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.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
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.
Multithreading and Garbage Collection Session 16.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
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 Jaanus Pöial, PhD Tallinn, Estonia.
Doing Several Things at Once
Multithreading / Concurrency
Java Multithreading.
Multithreading.
Multithreaded Programming in Java
Threads Chate Patanothai.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Multithreading in java.
Concurrent programming
Presentation transcript:

What is a ‘ thread ’ ? Free Online Dictionary of Computing (FOLDOC) Sharing a single CPU between multiple tasks (or "threads") in a way designed to minimize the time required to switch tasks. This is accomplished by sharing as much as possible of the program execution environment between the different tasks so that very little state needs to be saved and restored when changing tasks.

Basic knowleage A simplest java program is in multithread mode. The difference between C++ and Java when allocate and release memory ThreadGroup topGroup = Thread.currentThread().getThreadGroup().getParent(); topGroup.list();

DisplayThread class DisplayThreads { public static void main( String[] args ) { ThreadGroup topGroup = Thread.currentThread().getThreadGroup().getParent(); topGroup.list(); }

Output java.lang.ThreadGroup[name=system,maxpri=10] Thread[Reference Handler,10,system] Thread[Finalizer,8,system] Thread[Signal Dispatcher,10,system] Thread[CompilerThread0,10,system] java.lang.ThreadGroup[name=main,maxpri=10] Thread[main,5,main]

Concurrency Models I Processes versus Threads Operating System ThreadsFibresProcess thread library

Concurrent Programming in Java Lecture Aims To give an overview of the Java concurrency model and its relationship to other models To provide details of Java Threads

Concurrency Models II Java supports threads –Threads execute within a single JVM –Native threads map a single Java thread to an OS thread –Green threads adopt the thread library approach (threads are invisible to the OS) –On a multiprocessor system, native threads are required to get true parallelism (but this is still implementation dependent)

Concurrency Models III There are various ways in which concurrency can be introduced by –an API for explicit thread creation or thread forking –a high-level language construct such as PAR (occam), tasks (Ada), or processes (Modula) Integration with OOP, various models: –asynchronous method calls –early return from methods –futures –active objects Java adopts the active object approach

Concurrency Models IV Communication and Synchronization –approaches broadly classified as shared-variable or message passing –many different models, a popular one is a monitor –a monitor can be considered as an object where each of its operation executes in mutual exclusion encapsulated state procedural interface lock

Concurrency Models V Condition Synchronization –expresses a constraint on the ordering of execution of operations –e.g., data cannot be removed from a buffer until data has been placed in the buffer Monitors provide condition variables with two operations which can be called when the lock is held –wait: an unconditional suspension of the calling thread (the thread is placed on a queue associated with the condition variable) –notify: one thread is taken from the queue and re- scheduled for execution (it must reclaim the lock first) –notifyAll: all suspended threads are re-scheduled –notify and notifyAll have no effect if no threads are suspended on the condition variable

Java has a predefined class java.lang.Thread which provides the mechanism by which threads are created However to avoid all threads having to be child classes of Thread, it also uses a standard interface public interface Runnable { public void run(); } Hence, any class which wishes to express concurrent execution must implement this interface and provide the run method Threads do not begin their execution until the start method in the Thread class is called Concurrency in Java

Threads in Java Thread void run() void start()... Thread() Thread(Runnable target) subclass association MyThread void run() {... } RunnableObject void run() {... } parameter to Runnable implements void run()

Communication in Java Via reading and writing to data encapsulated in shared objects protected by simple monitors Every object is implicitly derived from the Object class which defines a mutual exclusion lock Methods in a class can be labeled as synchronized, this means that they can only be executed if the lock can be acquired (this happens automatically) The lock can also be acquired via a synchronized statement which names the object A thread can wait and notify on a single anonymous condition variable

The Thread Class public class Thread extends Object implements Runnable { public Thread(); public Thread(String name); public Thread(Runnable target); public Thread(Runnable target, String name); public Thread(Runnable target, String name, long stackSize); public void run(); public void start();... }

Thread Creation Either: 1.Extend Thread class and override the run method, or 2.Create an object which implements the Runnable interface and pass it to a Thread object via the Thread constructor How is the run method of Thread implemented?

Thread Creation: Robot Example Robot Motor Controller Thread is driven by User Interface controlled by 31

Classes for Robot public class UserInterface { // Allows the next position of the robot // to be obtained from the operator. public int newSetting (int dim) {... }... } public class Robot { // The interface to the Robot itself. public void move(int dim, int pos) {... } // Other methods, not significant here. } Note in Java 1.5, dimension would be an enumeration type

Motor Controller extends Thread I public class MotorController extends Thread { public MotorController(int dimension, UserInterface UI, Robot robo) { // constructor super(); dim = dimension; myInterface = UI; myRobot = robo; }

Motor Controller extends Thread II public void run() { int position = 0; // initial position int setting; while(true) { // move to position myRobot.move(dim, position); // get new offset and update position setting = myInterface.newSetting(dim); position = position + setting; } private int dim; private UserInterface myInterface; private Robot myRobot; } run method overridden

Motor Controller extends Thread III final int xPlane = 0; final int yPlane = 1; final int zPlane = 2; UserInterface UI = new UserInterface(); Robot robo= new Robot(); MotorController MC1 = new MotorController( xPlane, UI, robo); MotorController MC2 = new MotorController( yPlane, UI, robo); MotorController MC3 = new MotorController( zPlane, UI, robo); threads created

Motor Controller extends Thread IV When a thread is started, its run method is called and the thread is now executable When the run method exits, the thread is no longer executable and it can be considered terminated (Java calls this the dead state) The thread remains in this state until it is garbage collected In this example, the threads do not terminate MC1.start(); MC2.start(); MC3.start();

Warning The run method should not be called directly by the application. The system calls it. If the run method is called explicitly by the application then the code is executed sequentially not concurrently

Motor Controller implements Runnable I is driven by controlled by implements parameter to Robot Runnable MotorController Thread UserInterface

Motor Controller implements Runnable II public class MotorController implements Runnable { public MotorController(int Dimension, UserInterface UI, Robot robo) { // No call to super() needed now, // otherwise constructor is the same. } public void run() { // Run method identical. } // Private part as before. }

Motor Controller implements Runnable III final int xPlane = 0; final int yPlane = 1; final int zPlane = 2; UserInterface UI = new UserInterface(); Robot robo= new Robot(); MotorController MC1 = new MotorController( xPlane, UI, robo); MotorController MC2 = new MotorController( yPlane, UI, robo); MotorController MC3 = new MotorController( zPlane, UI, robo); No threads created yet

Motor Controller implements Runnable IV Thread X = new Thread(MC1); Thread Y = new Thread(MC2); Thread Z = new Thread(MC2); X.start(); Y.start(); Z.start(); constructors passed an object implementing the Runnable interface when the threads are created threads started Note: it is also possible to recommend to the JVM the size of the stack to be used with the thread. However, implementations are allowed to ignore this recommendation.

Thread Identification The identity of the currently running thread can be found using the currentThread method This has a static modifier, which means that there is only one method for all instances of Thread objects The method can always be called using the Thread class public class Thread extends Object implements Runnable {... public static Thread currentThread();... }

A Thread Terminates: when it completes execution of its run method either normally or as the result of an unhandled exception via a call to its stop method — the run method is stopped and the thread class cleans up before terminating the thread (releases locks and executes any finally clauses) –the thread object is now eligible for garbage collection. –stop is inherently unsafe as it releases locks on objects and can leave those objects in inconsistent states; the method is now deprecated and should not be used by its destroy method being called — destroy terminates the thread without any cleanup (not provided by many JVMs, now deprecated)

Daemon Threads Java threads can be of two types: user threads or daemon threads Daemon threads are those threads which provide general services and typically never terminate When all user threads have terminated, daemon threads can also be terminated and the main program terminates The setDaemon method must be called before the thread is started

Thread Revisited public class Thread extends Object implements Runnable {... public void destroy(); // DEPRECATED public final boolean isDaemon(); public final void setDaemon(); public final void stop(); // DEPRECATED }

Joining One thread can wait (with or without a timeout) for another thread (the target) to terminate by issuing the join method call on the target's thread object The isAlive method allows a thread to determine if the target thread has terminated

Thread Revisited public class Thread extends Object implements Runnable {... public final native boolean isAlive(); public final void join() throws InterruptedException; public final void join(long millis) throws InterruptedException; public final void join(long millis, int nanos) throws InterruptedException; }

Summary I: Java Thread States Non-Existing New Executable Blocked Dead start create thread object run method exits Non-Existing garbage collected and finalization wait, join notify, notifyAll thread termination destroy

Summary II The thread is created when an object derived from the Thread class is created At this point, the thread is not executable — Java calls this the new state Once the start method has been called, the thread becomes eligible for execution by the scheduler If the thread calls the wait method in an Object, or calls the join method in another thread object, the thread becomes blocked and no longer eligible for execution It becomes executable as a result of an associated notify method being called by another thread, or if the thread with which it has requested a join, becomes dead

Summary III A thread enters the dead state, either as a result of the run method exiting (normally or as a result of an unhandled exception) or because its destroy method has been called In the latter case, the thread is abruptly move to the dead state and does not have the opportunity to execute any finally clauses associated with its execution; it may leave other objects locked

Further Reading and Exercises Find out about Thread local data - use the web to search for “Java Thread Local Data” Do the Concurrent Hello World Exercise Do the Java Thread Scheduling Exercise Do Question 1.ii and 1.iii in the 2003 examination paper