THREAD MODEL
Multithreading in Java allows programs to execute multiple tasks simultaneously, utilizing the concept of threads. This paradigm enables efficient utilization of resources and enhances program performance. Java's support for multithreading facilitates the creation of robust and responsive applications, making it a pivotal feature for modern software development.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
THREAD MODEL 1
INTRODUCTION 1. Those who are familiar with the modern operation systems such as windows 95 may recognize that they can execute several programs simultaneously. This ability is known as multitasking. In System s terminology, it is called multithreading. 2. Multithreading is a conceptual programming paradigm where a program is divided into two or more subprograms, which can be implemented at the same time in parallel. For example, one subprogram can display an animation on the screen while another may build the next animation to be displayed. This something similar to dividing a task into subtasks and assigning them to different people for execution independently and simultaneously. 3. In most of our computers, we have only a single processor and therefore, in reality, the processor is doing only one thing at a time. However, the processor switches between the processes so fast that it appears to human beings that all of them are being done simultaneously. 4. Java programs contain only a single sequential flow of control. This is what happens when we execute a normal program. The program begins, runs through a sequence of executions, and finally ends. At any given point of time, there is only one statement under execution. 5. A thread is similar to a program that has a single flow of control. It has a beginning, a body and an end, and executes commands sequentially. In fact, all main programs in our earlier examples can be called single threaded programs. 6. A unique property of Java is its support for multithreading. That is, java enables us to use multiple flows of control in developing programs. Each flow of control may be thought of as in separate tiny program known as thread that runs in parallel to others. 2
SINGLE THREADED PROGRAM class ABC { } Beginning ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- Single threaded body of execution End 3
MULTITHREADED PROGRAM Main Thread _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ Main method module start start start _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ _______________ switching switching 4 Thread A Thread B Thread C
Introduction to Threads A java thread is an execution context or a lightweight process. It is a single sequential flow of control within a program. Java thread can be used to execute multiple tasks at the same time. Multitasking In computing, multitasking is a method by which multiple tasks, also known as processes, share common processing resources such as a CPU.
Introduction to Threads Contd., Multitasking Process Based Multitasking Thread Based Multitasking
Introduction to Threads Contd., Process Based Multitasking Thread Based Multitasking Is a Heavyweight Is a Light weight process process that runs in a and can run in a same different address space. address space so context switch or so, context switch or intercommunication intercommunication between processes is between processes is less expensive. much expensive.
Introduction to Threads Contd., A process that is made of one thread is known as single- threaded process. A process that creates two or more threads is called Multi-threaded process.
Multithreading Multithreading is the system environment where the tasks are sharing the same program under the multitasking environment. Multithreading is a subset of multitasking,since it concersn tasks which use the same program. Under the multithreading environment, a program is shared by several tasks concurrently. For each task, the program must work as if it were executing instructions exclusively for each task.
Benefits of Multithreading Improved performance Minimized system resource usage Simultaneous access to multiple applications Program structure simplification
Threads in Java The java.lang.Thread class is used to construct and access individual threads in a multithreaded application. It provides a thread API and all the generic behavior for threads. These behaviors include starting, sleeping, running, yielding, and having a priority.
Threads in Java Contd., Task of a Thread is defined in run() method: The run() method gives a thread something to do. Its code should implement the thread's running behavior. The first thread to be executed in a multithreaded process is called the main thread. The main thread is created automatically on the start up of Java program execution. MainThread.java
Life Cycle of a Thread The various states in the life cycle of a thread are: New Runnable Not Runnable Terminated or Dead
States of Thread New A thread object that is newly created. Syntax: Thread newThread = new Thread(this, threadName ); Runnable: When the start method of thread is invoked, the JVM calls the run method. Now the thread is ready to execute but not allocated to the processor, because the processor may be busy with another operation.
States of Thread Contd., Not Runnable: Sleep: When the sleep method of Thread class is called, the thread goes to the sleep state. When the time specified in the sleep method elapses, then the thread moves to runnable state. Wait: When the wait method is called, the thread goes to the wait state. It moves to runnable state when it is notified by another thread or time specified in the wait method elapses.
States of Thread Contd., Blocked When a thread is waiting for any I/O operations, it transitions to the blocked state. When the required resource is available, then it moves to runnable state. Dead When the thread completes execution, it transitions to the dead state.
Creating Threads There are two ways to create thread in java: Implement the Runnable interface (java.lang.Runnable) By Extending the Thread class (java.lang.Thread) The Runnable Interface Signature public interface Runnable { void run(); }
Creating Threads Contd., Extending Thread Class Public Class ThreadDemo extends Thread { Public void run() { //Task for thread defined. } }
Runnable Interface vs Thread Class When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class: Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface has this option. A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be expensive. Runnable Interface Demo Extending ThreadClass Demo Creating MultipleThreads Demo
Thread Priorities In Java we can specify the priority of each thread relative to other threads. Those threads having higher priority get greater access to available resources then lower priority threads. The following static final integer constants are defined in the Thread class: MIN_PRIORITY (0) Lowest Priority NORM_PRIORITY (5) Default Priority MAX_PRIORITY (10) Highest Priority
Thread Priorities Contd., The priority of an individual thread can be set to any integer value between and including the above defined constants. Thread s priority can be modified any time after its creation using the setPriority() method and its priority value can be retrieved using getPriority() method. When two or more threads are ready to be executed and system resource becomes available to execute a thread, the runtime system (the thread scheduler) chooses the Runnable thread with the highest priority for execution.
Thread Priorities Contd., If two threads of the same priority are waiting for the CPU, the thread scheduler chooses one of them to run in a > round-robin fashion. The chosen thread will run until one of the following conditions is true: A higher priority thread becomes Runnable. (Pre-emptive scheduling) It yields, or its run() method exits on systems that support time-slicing, its time allotment has expired ThreadPriorityDemo Heavy reliance on thread priorities for the behavior of a program can make the program non portable across platforms, as thread scheduling is host platform dependent.
Thread Synchronization With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object s value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.
Thread Synchronization Contd., Synchronization is based on the concept of monitor. The monitor controls the way in which synchronized methods access an object or class. To enter an object s monitor, you need to call a synchronized method or synchronized block. When a thread calls the wait() method, it temporarily releases the locks that it holds. In addition, the thread stops running and is added to the list of waiting threads for that object.
Thread Synchronization Contd., Synchronization is achieved using synchronized key word Synchronization is achieved in two ways: Syncronized methods Synchronized blocks
Synchronized Methods Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method s object or class. Synchronized methods are useful in situations where methods can manipulate the state of an object in ways that can corrupt the state if executed concurrently. A synchronized method can only use this current object.
Synchronized Methods Contd., Example: public synchronized void add(int value) { this.count += value; } SynchronizationMethodDemo
Synchronized Blocks synchronized block you may lock on an object other than this which allows to be much more flexible. Example: public void add(int value){ Student s=new Student(); synchronized(s) { this.count += value; } } SynchronizationBlockDemo
Inter-Thread Communication Communication between threads is known as Interthreaded communication. Java provides well designed inter-process mechanism using the wait(), notify() and notifyAll() methods. wait() tells the calling thread to exit and enter the sleep state till some other thread enters and calls notify() public final void wait() throws InterruptedException public final notify() notifyAll() wakes up or notifies all the threads that called wait( Joining Threads: A thread invokes the join() method on another thread in order to wait for the other thread to complete its execution.
Wait-Notify Mechanism First thread notify( ) notify( ) wakes up or notifies the first thread. notifyAll( ) wakes up Thread 2 notifyAll( ) Thread 3 Thread 1 or notifies all the threads that called wait( ) on the same object. InterThreadCommDemo(Producer Consumer.java) JoinDemo
7. A program that contains multiple flows of control is known as multithreaded program. 8. The above fig. is a java program with four threads, one main and three others. The main thread is actually the main method module, which is designed to create and start the other three threads, namely A, B and C 9. Once initiated by the main thread, the threads A, B and C run concurrently and share the resources jointly. The ability of a language to support multithreads is referred to as concurrency. 10. Threads in java are subprograms of main application program and share the same memory space, they are known as lightweight threads or lightweight processes.. Note: really mean that they actually run at the same time. Since all the threads are running on a single processor, the flow of execution is shared between the threads. It is important to remember that threads running in parallel does not 31
CREATING THREADS 1. Creating threads in Java is simple. 2. Threads are implemented in the form of objects that contain a method called run(). 3. The run() method is the heart and soul of any thread. It makes up the entire body of a thread and is the only method in which the thread s behaviour can be implemented. 4. A typical run() would appear as follows: public void run() { } ------------------ ------------------ ------------------ Statements for implementing thread 32
5. The run() method should be invoked by an object for the concerned thread. 6. This can be achieved by creating the thread and initiating it with the help of another thread method called start(). 7. A new thread can be created in two ways. a. By creating a thread class: Define a class that extends Thread class and override its run() method with the code required by the thread. b. By converting a class to a thread: Define a class that implements Runnable interface. The Runnable interface has only one method, run(), that is to be defined in the method with the code to be executed by the thread. 33
EXTENDING THE THREAD CLASS We can make our class runnable as a thread by extending the class java.lang.Thread. This gives us access to all the thread methods directly. It includes the following steps: 1. Declare the class as extending the Thread class 2. Implement the run() method that is responsible for executing the sequence of code that the thread will execute. 3. Create a thread object and call the start() method to initiate the thread execution. 1. Declaring the class class MyThread extends Thread { --------------- --------------- --------------- --------------- } 34
2. Implementing the run() Method public void run() { } ----------------- ----------------- ----------------- ----------------- Thread Code Here 3. Starting New Thread MyThread aThread = new MyThread(); aThread.start(); //Invoke run() method 35
Creating threads using the thread class class A extends Thread { public void run() { } } class B extends Thread { public void run() { } } for(int i = 1;i <= 5;i++) { System.out.println("\tFrom Thread A : i = " + i); } System.out.println("Exit from A "); for(int j = 1;j <= 5;j++) { System.out.println("\tFrom Thread B : j = " + j); } System.out.println("Exit from B "); 36
class C extends Thread { public void run() { } } class ThreadTest { public static void main(String args[]) { A a = new A(); B b = new B(); C c = new C(); for(int k = 1;k <= 5;k++) { System.out.println("\tFrom Thread C : k = " + k); } System.out.println("Exit from C "); } } a.start(); b.start(); c.start(); 37
IMPLEMENTING THE RUNNABLE INTERFACE implementing threads in our programs. To do this, we must perform the steps listed below: The Runnable interface declares the run() method that is required for 1. Declare the class an implementing the Runnable interface. 2. Implementing the run() method. 3. Create a thread by defining an object that is instanitiated form the runnable class as the target of the thread. 4. Call the thread s start() method to run the thread. 38
import java.lang.Thread; class X implements Runnable { public void run() { } } class Y implements Runnable { public void run() { } } for(int i = 1;i <= 5;i++) { } System.out.println("Exit from A "); System.out.println("\tFrom Thread A : i = " + i); for(int j = 1;j <= 5;j++) { System.out.println("\tFrom Thread B : j = " + j); } System.out.println("Exit from B "); 39
class Z implements Runnable { public void run() { } } for(int k = 1;k <= 5;k++) { System.out.println("\tFrom Thread C : k = " + k); } System.out.println("Exit from C "); class RunnableTest { public static void main(String args[]) { X runnableX = new X(); Thread threadX = new Thread(runnableX); Y runnableY = new Y(); Thread threadY = new Thread(runnableY); Z runnableZ = new Z(); Thread threadZ = new Thread(runnableZ); } } threadX.start(); threadY.start(); threadZ.start(); 40
LIFE CYCLE OF A THREAD During the life time of a thread, there are many states it can enter. They include 1. Newborn state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state 41
State Transition diagram of a Thread New Thread Newborn start stop Active Thread stop Runnable Running Dead yield Killed Thread suspend resume stop sleep notify wait Idle Thread Blocked (Not Runnable) 42
Newborn State When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state, we can do only one of the following things with it: 1. schedule it for funning using start() method. 2. kill it using stop() method. Newborn start stop Runnable state Dead State 43
Runnable State 1. The runnable state means that the thread is ready for execution and is waiting for the availability of processor. 2. That is, the thread has joined the queue of threads that are waiting for execution. 3. If all threads have equal priority, then they are given time slots for execution in round robin fashion. i.e., first come, first serve manner. 4. The thread that relinquishes contol joins the queue at the end and again waits for its turn. This process of assigning time to threads is known as time slicing. 5. However, if we want a thread to relinquish control to another thread of equal priority before its turn comes, we can do so by using the yield() method. Yield() 44 Running Thread
Running State Running means that the processor has given its time to the thread for its execution. The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread. A running thread may relinquish its control in one of the following situations: 1. suspend() and resume() It has been suspended using suspend() method. A suspended thread can be revived by using the resume() method. This approach is useful when we want to suspend a thread for some time due to certain reason, bur do not want to kill it suspend() resume() Suspended Running Runnable 45
2. sleep() It has been made to sleep, We can put a thread to sleep for a specified time period using the method sleep (time) where time is in milliseconds. This means that the thread is out of the queue during this time period. The thread re enters the runnable state as soon as this time period is elapsed. sleep (t) after t Sleeping Running Runnable 46
3. wait() and notify() It has been told to wait until some event occurs. This is done using the wait() method. The thread can be scheduled to run again using the notify() method. wait() notify () Running Runnable Waiting Blocked State 1. A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. 2. This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain requirements. 3. A blocked thread is considered not runnable but not dead therefore fully qualified to run again. 47
Dead State 1. Every thread has life cycle. A running thread ends its life when it has completed executing its run() method. 2. It is a natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death to it. 3. A thread can be killed as soon it is born, or while it is running, or even when it is in notrunnable (blocked) condition. 48
import java.lang.Thread; class A extends Thread { public void run() { } } class B extends Thread { public void run() { } } for(int i = 1;i <= 5;i++) { if(i == 1) yield(); System.out.println("\tFrom Thread A : i = " + i); } System.out.println("Exit from A "); for(int j = 1;j <= 5;j++) { System.out.println("\tFrom Thread B : j = " + j); if(j==3) stop(); } System.out.println("Exit from B "); 49
class C extends Thread { } class ThreadTest_1 { public void run() { } for(int k = 1;k <= 5;k++) { } System.out.println("Exit from C "); System.out.println("\tFrom Thread C : k = " + k); if(k==1) try { sleep(1000); } catch(Exception e) { } public static void main(String args[]) { A a = new A(); B b = new B(); C c = new C(); System.out.println("Start Thread A"); a.start(); System.out.println("Start Thread B"); b.start(); System.out.println("Start Thread C"); c.start(); } } System.out.println("End of main Thread"); 50