Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.

Slides:



Advertisements
Similar presentations
3.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition Process An operating system executes a variety of programs: Batch system.
Advertisements

1 CSC321 §2 Concurrent Programming Abstraction & Java Threads Section 2 Concurrent Programming Abstraction & Java Threads.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
CSC 501 Lecture 2: Processes. Von Neumann Model Both program and data reside in memory Execution stages in CPU: Fetch instruction Decode instruction Execute.
Thread Control methods The thread class contains the methods for controlling threads Thread() create default thread Thread(target: runnable ) creates new.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Object-Oriented Software Engineering Concurrent Programming.
Ceng Operating Systems Chapter 2.1 : Processes Process concept Process scheduling Interprocess communication Deadlocks Threads.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
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.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Phones OFF Please Processes Parminder Singh Kang Home:
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Lecture 4 : JAVA Thread Programming
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
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.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
© 2004, D. J. Foreman 2-1 Concurrency, Processes and Threads.
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.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
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.
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
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.
Threading and Concurrency COM379T John Murray –
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.
© Wang Bin 2004 Java Threads. © Wang Bin 2004 In this lesson, you will learn to: u Define the concepts of threads and multithreading  Identify the functions.
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.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
CMSC 330: Organization of Programming Languages 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.
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.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
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.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Multithreading / Concurrency
Multithreading Lec 23.
Multi Threading.
Java Multithreading.
Multithreading.
Concurrency, Processes and Threads
Chapter 2 Processes and Threads Today 2.1 Processes 2.2 Threads
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Programming with Shared Memory Java Threads and Synchronization
Computer Science 2 06A-Java Multithreading
Multithreading in java.
CS510 Operating System Foundations
Threads and Multithreading
Concurrency, Processes and Threads
Lecture 19 Threads CSE /6/2019.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note

Process Operating system abstraction to represent what is needed to run a single program a sequential streamof execution in its own address space

Switch from process to process PCB

UNIX process Every process, except process 0, is created by the fork() system call fork() allocates entry in process table and assigns a unique PID to the child process child gets a copy of process imageof parent both child and parent are executing the same code following fork()

Process Creation main () { int pid; cout<< “just one process so far”<<endl; pid= fork(); if (pid==0) cout<<“im the child“<< endl; else if (pid> 0) cout<<“im the parent”<< endl; else cout<< “fork failed”<< endl; }

Threads Definition single sequential flow of controlwithin a program A thread runs within the context of a program’s process and takes advantage of the resources allocatedfor that process and it’s environment Each thread is comprised of (from OS perspective) Program counter Register set Stack Threads belonging to the same process share Code section Data section OS resources such as open files

Single and multithreaded program Shared among threads

Multi-process vs Multi-thread Process Child process gets a copy of parents variables Relatively expensive to start Don't have to worry about concurrent access to variables Thread Child process shares parent’s variables Relatively cheap to start Concurrent access to variables is an issue

Implementing processes -the OS view

Programming JAVA threads

JAVA Threading Models Java has threads built-in (java.lang.thread) Applications consist of at least one thread Often called ‘main’ The Java Virtual Machine creates the initial thread which executes the main method of the class passed to the JVM The methods executed by the ‘main’ thread can then create other threads

Creating Threads : method 1 A Thread class manages a single sequential thread of control. The Thread class executes instructions from its method run(). Thread t = new MyThread(); t.start(); Note: “start()”is a native method. And the invocation returns immediately to the caller

Thread Creation Example

Creating Threads : method 2 Since Java does not permit multiple inheritance, we often implement the run() method in a class not derived from Thread but from the interface Runnable.

Creating & Executing Threads, (Runnable) Runnable interface has single method public void run() Implement a Runnable and define run() class MyRunnable implements Runnable{ public void run() { System.out.println(“MyRunnable.run()”); } //other methods and data for this class }

Creating & Executing Threads, (Runnable) Class Main { public static void main(String[] args) { MyRunnable myrun= new MyRunnable(); Thread t1 = new Thread(myrun); t1.start(); System.out.println(“InsideMain()”); } Thread’s run() method invokes the Runnable’s run() method

Example : Self-starting Threads class AutoRun implements Runnable{ public AutoRun() { new Thread(this).start(); } public void run() { System.out.println(“AutoRun.run()”); } class Main { public static void main(String[] args) { AutoRunt1 = new AutoRun(); System.out.println(“InsideMain()”); }

Thread Names All threads have a name to be printed out. The default name is of the format: Thread-No Thread-1, Thread-2, … User-deinfed names can be given thru constructor: Thread myThread= new Thread(“HappyThread”); Or using the “ setName(aString) ”method. There is a method in Thread class, called “getName()”, to obtain a thread’s name

Thread Life-Cycle

Alive States Once started, an alivethread has a number of substates

Thread Priority All Java threads have a priority value, currently 1 and 10. Priority can be changed at any time setPriority(int newPriority) Initial priority is that of the creating thread Preemptive scheduling JVM gives preference to higher priority threads. (Not guaranteed)

yield Release the right of CPU static void yield() allows the scheduler to select another runnable thread (of the same priority) no guarantees as to which thread

Thread identity Thread.currentThread() Static method Returns reference to the running thread Compare running thread with created thread class AutoRun implements Runnable{ private Thread _me; public AutoRun() { me_ = new Thread(this); me_.start(); }

public void run() { if (_me == Thread.currentThread()) System.out.println(“AutoRun.run()”); } class Main { public static void main(String[] args) { AutoRun t1 = new AutoRun(); t1.run(); //no printout System.out.println(“InsideMain()”); }

Thread sleep, suspend, resume static void sleep(long millis) Blocks this thread for at least the time specified void stop(), void suspend(), void resume() Deprecated!

Thread Waiting & Status Check void join(), void join(long), void join(long, int) One thread (A) can wait for another thread (B) to end // in thread A threadB.join() boolean isAlive() returns true if the thread has been started and not stopped

Joining a Thread public class JoinThr { static public void main(String s[]) { MyThread1 Thread_a; // Define a Thread MyThread2 Thread_b; // Define another Thread Thread_a = new MyThread1(); Thread_b = new MyThread2(Thread_a); // Start the threads System.out.println("Startingthe threads..."); Thread_a.start(); Thread_b.start(); }

Joining a Thread : MyThread1 // Thread class that just prints a message 5 times class MyThread1extends Thread { public void run(){ System.out.println(getName() + " is running..."); for (int i=0; i<4; i++) { try { // Sleep a bit sleep(500); } catch (InterruptedExceptione) {} System.out.println("Hellothere, from”+getName()); }

Joining a Thread : MyThread2 class MyThread2extends Thread { private Thread wait4me; // Thread to wait for // Constructor MyThread2(Thread target) { super(); wait4me = target; } public void run(){ System.out.println(getName() + " is waiting for " + wait4me.getName() + "..."); try { // wait for target thread to finish wait4me.join(); } catch (InterruptedExceptione) {} // …

Joining a Thread : MyThread2 System.out.println(wait4me.getName() + "has finished..."); // Print message 4 times for (inti=0; i<4; i++) { try { // Sleep a bit sleep(500); } catch (InterruptedExceptione) {} System.out.println("Hellothere, from " + getName()); }

Output result Hello There, From Thread-4 Thread-4 has finished.. Hello There, From Thread-5

Thread synchronization The advantage of threads is that they allow many things to happen at the same time The problem with threads is that they allow many things to happen at the same time Safety Nothing bad ever happens no race condition Liveness Something eventually happens : no deadlock

Race condition example class Account { int balance; public void deposit(int val) { balance = balance + val; }

Thread Synchronization

Synchronized Access to Shared Data

Synchronized JAVA methods We can control access to an object by using the synchronized keyword Using the synchronized keyword will force the lock on the object to be used

Synchronized Lock Object Every Java object has an associated lock acquired via synchronized statements (block) synchronized(anObject){ // execute code while holding anObject's lock } Only one thread can hold a lock at a time Lock granularity: small critical section is better for concurrencyobject