Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.

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.
Thread Control methods The thread class contains the methods for controlling threads Thread() create default thread Thread(target: runnable ) creates new.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
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-
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Java Programming, Second Edition Chapter Seventeen Multithreading and Animation.
1 Java Threads Instructor: Mainak Chaudhuri
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.
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.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
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.
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.
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.
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.
1 Introduction to Threads Computers can perform many tasks concurrently – download a file, print a file, receive , etc. Sequential languages such.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
Multithreading Chapter Introduction Consider ability of _____________ to multitask –Breathing, heartbeat, chew gum, walk … In many situations we.
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
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.
Multi-Threading in Java
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 More on Thread API.
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.
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 and Multithreading. Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three general approaches:
Multithreading and Garbage Collection Session 16.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
THREAD MODEL.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Multithreading & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
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.
1 Multithreading in Java THETOPPERSWAY.COM. 2 Outline  Multithreading & Thread Introduction  Creating threads  Thread Life Cycle  Threads priorities.
Java Thread Programming
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multithreading Lec 23.
Multi Threading.
Java Multithreading.
Lecture 9 Object Oriented Programming Using Java
Multithreading.
Multithreaded Programming in Java
Multithreading in Java
More About Threads.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
21 Threads.
Multithreading in java.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Introduction to Threads Session 01

Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading Create threads Discuss thread states Manage threads Explain how to set thread priorities Describe a daemon thread

Java Simplified / Session 14 / 3 of 28 Multitasking Vs Multithreading Multitasking is the ability to run one or more programs concurrently. Operating system controls the way in which these programs run by scheduling them. Time elapsed between switching of programs is minuscule. Multithreading is the ability to execute different parts of a program called threads, simultaneously.

Java Simplified / Session 14 / 4 of 28 Thread Thread is the smallest unit of executable code that performs a particular task. An application can be divided into multiple tasks and each task can be assigned to a thread. Many threads executing simultaneously is termed as Multithreading. Appears that the processes are running concurrently, but it is not so.

Java Simplified / Session 14 / 5 of 28 Benefits of Multithreading Multithreading requires less overhead than multitasking. In multitasking, processes run in their own different address space. Tasks involved in multithreading can share the same address space. Inter-process calling involves more overhead than inter-thread communication. Multithreading allows us to write efficient programs that make maximum use of CPU. Multithreading allows animation loops to sleep for a second between each frame without causing the whole system to pause.

Java Simplified / Session 14 / 6 of 28 Applications of thread Displaying scrolling text patterns or images on the screen Playing sound and displaying images simultaneously Displaying multiple images on the screen

Java Simplified / Session 14 / 7 of 28 Creating threads It is this thread from which child threads are created. Program is terminated when main thread stops execution. Main thread can be controlled through Thread objects. Reference of the main thread can be obtained by calling the currentThread() method of the Thread class. When Java programs execute, there is always one thread running and that is the main thread.

Java Simplified / Session 14 / 8 of 28 Creating threads Contd… While using applets, Thread class cannot be extended. Therefore one has to implement the Runnable interface. Thread objects can be created in two ways: Declare a class that is a sub-class of the class Thread defined in java.lang package class mythread extends Thread Declare a class that implements the Runnable interface class mythread implements Runnable

Java Simplified / Session 14 / 9 of 28 Creating threads Contd… When start() method is invoked, the system resources required to run the thread is created and schedules the thread to run. It then calls the thread’s run() method. After a new thread has been initiated, we use the start() method to start the thread otherwise it is an empty Thread object with no system resources allocated. Mythread t = new Mythread(); t.start();

Java Simplified / Session 14 / 10 of 28 public void run() { while(true) { try { System.out.println("This is the child thread"); Thread.sleep(500); } catch(InterruptedException e) { } } Creating threads Contd… Example 1 – Creating a thread by extending the Thread class class MyThread extends Thread { public static void main(String args[]) { MyThread Objex = new MyThread(); Objex.create(); System.out.println("This is the main thread"); } public void create() { Thread Objth = new Thread(this); Objth.start(); } Output

Java Simplified / Session 14 / 11 of 28 Creating threads Contd… Example2 – Creating a thread by implementing the Runnable interface class MyThread2 implements Runnable { public static void main(String args[]) { MyThread2 Objx = new MyThread2(); Objx.create(); System.out.println("This is the main thread"); } public void create() { Thread Objth = new Thread(this); Objth.start(); } public void run() { while(true) { try { System.out.println("This is the child thread"); Thread.sleep(500); } catch(InterruptedException e) { } } Output

Java Simplified / Session 14 / 12 of 28 Thread states Born: A newly created thread is in a born state. Ready: After a thread is created, it is in its ready state waiting for start() method to be called.

Java Simplified / Session 14 / 13 of 28 Thread states Contd… Running: Thread enters the running state when it starts executing Sleeping: Execution of a thread can be halted temporarily by using sleep() method. The thread becomes ready after sleep time expires.

Java Simplified / Session 14 / 14 of 28 Thread states Contd… Waiting: Thread is in waiting state if wait() method has been invoked. Used when two or more threads run concurrently. Blocked: The thread enters a blocked state when it waits for an event such as Input/Output operations. Dead: The thread enters the dead state after the run() method has finished or the threads stop() method is called.

Java Simplified / Session 14 / 15 of 28 Different thread states New Thread (BORN) READY RUNNING DEAD SLEEPING WAITINGBLOCKED

Java Simplified / Session 14 / 16 of 28 Some methods of thread class final boolean isAlive() : returns true if the thread is alive. final String getName() : returns the name of the thread. void start() : used to start a thread by calling the method run().

Java Simplified / Session 14 / 17 of 28 Some methods of thread class Contd… final void join() throws InterruptedException: waits for the thread to die. static void yield(): causes the currently executing thread to temporarily pause and allow other threads to execute. final void setName(String name): sets the name of the thread to the name that is passed as an argument.

Java Simplified / Session 14 / 18 of 28 Some methods of thread class Contd… final boolean isDaemon(): checks if the thread is a Daemon thread. static int activeCount(): returns the number of active threads. static void sleep(): used to suspend a thread for a certain period of time.

Java Simplified / Session 14 / 19 of 28 Conditions that prevent thread execution Put to sleep using sleep() method Is waiting because wait() method was called Explicitly yielded using yield() method Blocked for file I/O If thread is: Not of highest priority

Java Simplified / Session 14 / 20 of 28 Managing threads Similarly while programming, we may have to run a thread of higher importance without stopping or suspending the current running thread Thread priorities play an important role in such a situation. Priorities for carrying out activities changes at times eg :Planned to visit museum in the afternoon but due to toothache, had to go to doctor

Java Simplified / Session 14 / 21 of 28 Thread priorities in Java are constants defined in the Thread class. NORM_PRIORITY – value is MAX_PRIORITY – value is MIN_PRIORITY – value is Managing threads Contd… The default priority is NORM_PRIORITY Two methods used to change priority:  final void setPriority(int newp): changes the thread’s current priority.  final int getPriority(): returns the thread’s priority.

Java Simplified / Session 14 / 22 of 28 Daemon threads Two types of threads in Java: User threads: created by the user Daemon threads: threads that work in the background providing service to other threads e.g. – the garbage collector thread When user thread exits, JVM checks to find out if any other thread is running. If there are, it will schedule the next thread. If the only executing threads are daemon threads, it exits.

Java Simplified / Session 14 / 23 of 28 Daemon threads Contd… We can set a thread to be a Daemon if we do not want the main program to wait until a thread ends. Thread class has two methods to deal with Daemon threads: public final void setDaemon(boolean value) : sets a thread to be a daemon thread public final boolean isDaemon() : checks if the given thread is a daemon thread

Java Simplified / Session 14 / 24 of 28 Daemon threads Contd… An example class TestDaemon implements Runnable { Thread Objth1,Objth2; public TestDaemon() { Objth1 = new Thread(this); Objth1.start(); Objth2 = new Thread(this); Objth2.setDaemon(true); } public void run() { System.out.println(Thread.activeCount()); System.out.println(Objth1.isDaemon()); System.out.println(Objth2.isDaemon()); } public static void main(String args[]) { new TestDaemon(); } Output

Java Simplified / Session 14 / 25 of 28 Summary Multithreading allows programmers to write efficient programs that make the maximum use of the CPU. Java provides built-in support for multithreading in the form of classes and interfaces. When Java programs are executed, there is already one thread that is running and it is the main thread. This main thread is important for two reasons: It is the thread from which child threads will be created. Program is terminated when the main thread stops execution. Thread objects can be created in two ways: Declare the class to be a sub-class of the Thread class where we need to override the run() method of the Thread class. Declare a class that implements the Runnable interface. Then define the run() method. Each thread in a Java program is assigned a priority, and the Java Virtual Machine never changes the priority of a thread.

Java Simplified / Session 14 / 26 of 28 Summary Contd… The default priority of a thread that is created is 5. Two of the constructors in the Thread class are: public Thread(String threadname) public Thread( ) There are two types of threads in a Java program: User threads and Daemon threads The threads created by the user are called user threads. The threads that are intended to be "background" threads, providing service to other threads are referred to as daemon threads. The Thread class has two methods that deal with daemon threads. public final void setDaemon(boolean on) public final boolean isDaemon( )