Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.

Slides:



Advertisements
Similar presentations
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Advertisements

Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Slides 8c-1 Programming with Shared Memory Java Threads and Synchronization Review The following notes are based upon the Java tutorial at
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
ThreadThread Thread Basics Thread Synchronization Animations.
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-
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
1 Java Threads and Synchronization Review Modified from slides taken from
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
10/10/20151 MULTITHREADED PROGRAMMING. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
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.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
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.
1 Web Based Programming Section 8 James King 12 August 2003.
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. Concurrent programming in Java How to make all things run-able?
Threads.
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.
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
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Threading and Concurrency COM379T John Murray –
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.
Java 3: Odds & Ends Advanced Programming Techniques.
© 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.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
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.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
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.
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.
Advanced Programming Concurrency and Threads Advanced Programming. All slides copyright: Chetan Arora.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Java Multithreading.
Lecture 9 Object Oriented Programming Using Java
Multithreading.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
CNT 4007C Project 2 Good morning, everyone. In this class, we will have a brief look at the project 2. Project 2 is basically the same with project 1.
Java Based Techhnology
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
برنامه‌نویسی چندنخی Multi-Thread Programming
Threads in Java James Brucker.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads in Java

Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including memory space. –Synonymous with program or application. –Most implementations of the Java virtual machine run as a single process.

Processes and Threads Threads –A thread is a flow of control –A thread is a series of executed statements –A thread is a nested sequence of method calls. –Threads exist within a process Every process has at least one. –Start execution with “Main Thread” but an application can be divided into many. –Concurrent programming

Multiple Threads

Creating Threads Program always has at least one thread: the one created when the program begins execution. In a normal Java application program, this thread starts at the beginning of main(). To start the execution of a thread, you call the start() method for the Thread object. The code that executes in a new thread is always a method called run(), which is public, accepts no arguments, and doesn’t return a value. Threads other than the main thread in a program always start in the run() method for the object that represents the thread.

Threads

Defining and Starting a Thread Create an object of java.lang.Thread class. Two ways. 1.One way is to define your class as a subclass of Thread and provide a definition of the method run(), which overrides the inherited method. 2.The other possibility is to define your class as implementing the interface Runnable, which declares the run() method, and then create a Thread object in your class when you need it.

Thread Class Methods Method Meaning getName Obtain a thread’s name. getPriority Obtain a thread’s priority. isAlive Determine if a thread is still running. join Wait for a thread to terminate. run Entry point for the thread. sleep Suspend a thread for a period of time. start Start a thread by calling its run method.

Single Thread: Example // Controlling the main Thread. class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); // change the name of the thread t.setName("My Thread"); System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); }}}

Single Thread: Example Output Current thread: Thread[main,5,main] After name change: Thread[My Thread,5,main]

Runnable Object The Runnable interface defines a single method, run, meant to contain the code executed in the thread.

Example 1: Through Runnable Interface public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new Thread(new HelloRunnable())).start(); }

public class HR implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { HR r=new HR(); Thread t=new Thread(r); t.start(); } } Example 1: Through Runnable Interface

SubClass Thread An application can subclass Thread, providing its own implementation of run.

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

public class HR extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { HR r=new HR(); r.start(); } } Example: Through Thread Class

Pausing Execution with Sleep Thread.sleep causes the current thread to suspend execution for a specified period. sleep(). –Takes time in milliseconds Interrupts can terminate the sleep period.

Example 1: Sleep Message public class SleepMessages { public static void main(String args[]) throws InterruptedException { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too“ }; for (int i = 0; i < importantInfo.length; i++) { Thread.sleep(4000); System.out.println(importantInfo[i]); }

OUTPUT: Sleep Message

class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500);}} catch (InterruptedException e) { System.out.println("Child interrupted.");} System.out.println("Exiting child thread.");}} Example 2: Through Runnable Interface

class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); }} catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting.");}} Example 2: Through Runnable Interface

Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting. Example 2: Through Runnable Interface Output

Stopping Threads: Interrupt An interrupt is an indication to a thread that it should stop what it is doing and do something else. A thread sends an interrupt by invoking interrupt() on the Thread object.

Interrupt Status Flag Interrupt status flag Invoking Thread.interrupt sets the flag MethodDescription isInterrupted() Check if the thread's interrupt() method has been called (this does not clear the interrupted flag). isAlive() Tests if this thread is alive. A thread is alive if it has been started and has not yet died.

Daemon and User Threads The call to setDaemon(true), in the TryThread constructor makes the thread that is created a daemon thread A daemon thread: – Background thread that is subordinate to the thread that creates it. – When the thread that created the daemon thread ends, the daemon thread dies with it. –Threads that run indefinitely should usually defined as daemon threads

Daemon and User Threads A thread that is not a daemon thread is called a user thread : –Typically used for threads that run finite time –It must be explicitly stopped or destroyed, or its run method must return You can only call setDaemon() for a thread before it starts

Daemon and User Threads Main Thread thread1.setDaemon(true); thread1.start(); thread2.setDaemon(true); thread2.start(); thread3.start(); return; Main Thread thread1.setDaemon(true); thread1.start(); thread2.setDaemon(true); thread2.start(); thread3.start(); return; thread 1 created as a daemon thread thread 1 created as a daemon thread thread 2 created as a daemon thread thread 2 created as a daemon thread thread 3 created as a user thread thread 3 created as a user thread Ends the main thread. All daemon threads created in the main thread will end at this point Must be explicitly stopped or destroyed, or its run method must return

Example import java.io.IOException; public class TryThread extends Thread { public TryThread(String firstName, String secondName, long delay) { this.firstName = firstName; // Store the first name this.secondName = secondName; // Store the second name aWhile = delay; // Store the delay setDaemon(true); // Thread is daemon } public static void main(String[] args) { // Create three threads Thread first = new TryThread("Hopalong ", "Cassidy ", 200L); Thread second = new TryThread("Marilyn ", "Monroe ", 300L); Thread third = new TryThread("Slim ", "Pickens ", 500L); System.out.println("Press Enter when you have had enough...\n");

Example first.start(); // Start the first thread second.start(); // Start the second thread third.start(); // Start the third thread try { System.in.read(); // Wait until Enter key pressed System.out.println("Enter pressed...\n"); } catch (IOException e) { // Handle IO exception System.out.println(e); // Output the exception } System.out.println("Ending main()"); return; } // Method where thread execution will start public void run() { try {

Example while(true) { // Loop indefinitely... System.out.print(firstName); // Output first name sleep(aWhile); // Wait aWhile msec. System.out.print(secondName + "\n"); // Output second name } catch(InterruptedException e) { // Handle thread interruption System.out.println(firstName + secondName + e); // Output the exception } private String firstName; // Store for first name private String secondName; // Store for second name private long aWhile; // Delay in milliseconds }

Output

Connecting Threads Calling the join() method with no arguments will halt the current thread for as long as it takes the specified thread to die or with argument to specify the number of milliseconds to wait for the death of a thread thread1.join(); // suspend the current thread until the thread1 dies thread1.join(1000); // Wait up to 1 second for thread1 to die

Thread Scheduling

Synchronization The objective of synchronization is to ensure that when several threads want access to a single resource, only one thread can access it at any given time. Two ways to manage threads –manage code at the method level. –manage code at the block level

t Why to synchronize ? i = i + 1; (i = 31) i = i + 1; (i = 31) starting value of i is 30 i = i - 1; value of i is 31 ?? (it should be 30) value of i is 31 ?? (it should be 30) thread 2 thread 1 i 30 i 29

Synchronized Methods Make methods mutually Exclusive. Using keyword Synchronized. Locking and Unlocking

Example class MyClass { synchronized public void method1() { // Code for the method... } synchronized public void method2() { // Code for the method... } public void method3() { // Code for the method... } For the same object instance only one synchronized method can be executing at one time, because that method will have set the lock that prevents any other synchronized method from starting.

Example

LAB TASK 1 1.Create a simple java program 2.Having just one thread - the main thread. 3.Add a function which contains a loop that runs 10 times. 4.Display the name of the thread at each step with “1 sec” pause at each step. Note: Code Must handle Interrupted Exception

Output output: thread main step 0 thread main step 1 thread main step 2 thread main step 3... … thread main step 99

LAB TASK 2 1.Creating two parallel threads in “Main Thread” by implementing the Runnable interface 2.Add a "run" method. { write for loop which displays the names of threads} 3.Start both threads in Main 4.Introduce the delay of “1 sec” for overlapping execution of both threads.

Output output: thread Thread-0 step 0 thread Thread-1 step 0 thread Thread-0 step 1 thread Thread-1 step 1 thread Thread-0 step 2 thread Thread-1 step 2 thread Thread-0 step 3 thread Thread-1 step 3...

LAB TASK 3 Repeat “LAB TASK 2” by deriving our class from the "Thread" class.

Output output: thread Thread-0 step 0 thread Thread-1 step 0 thread Thread-0 step 1 thread Thread-1 step 1 thread Thread-0 step 2 thread Thread-1 step 2 thread Thread-0 step 3 thread Thread-1 step 3...