Presentation is loading. Please wait.

Presentation is loading. Please wait.

THREAD MODEL.

Similar presentations


Presentation on theme: "THREAD MODEL."— Presentation transcript:

1 THREAD MODEL

2 INTRODUCTION 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. 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. 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. 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. 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. 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.

3 SINGLE THREADED PROGRAM
class ABC { } Beginning Single – threaded body of execution End

4 MULTITHREADED PROGRAM
Main Thread _______________ Main method module start start start _______________ _______________ _______________ switching switching Thread A Thread B Thread C

5 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.

6 Introduction to Threads – Contd.,
Multitasking Process Based Multitasking Thread Based Multitasking

7 Introduction to Threads – Contd.,
Process Based Multitasking Is a Heavyweight process that runs in a different address space. so, context switch or intercommunication between processes is much expensive. Thread Based Multitasking Is a Light weight process and can run in a same address space so context switch or intercommunication between processes is less expensive. 

8 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.

9 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.”

10 Benefits of Multithreading
Improved performance Minimized system resource usage Simultaneous access to multiple applications Program structure simplification

11 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. Faculty Guide Lines Explain Thread model in Java Explain java.lang.Thread class and built-in methods in it. Demo on Main thread is given.

12 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. Faculty Guide Lines Explain Thread model in Java Explain java.lang.Thread class and built-in methods in it. Demo on Main thread is given. MainThread.java

13 Life Cycle of a Thread The various states in the life cycle of a thread are: New Runnable Not Runnable Terminated or Dead

14 States of Thread New Runnable: Syntax:
A thread object that is newly created. Syntax: 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. Thread newThread = new Thread(this,”threadName”);

15 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.

16 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.

17 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(); }

18 Creating Threads – Contd.,
Extending Thread Class Public Class ThreadDemo extends Thread { Public void run() { //Task for thread defined. } }

19 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

20 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

21 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.

22 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.

23 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.

24 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.

25 Thread Synchronization – Contd.,
Synchronization is achieved using synchronized key word Synchronization is achieved in two ways: Syncronized methods Synchronized blocks

26 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.

27 Synchronized Methods – Contd.,
Example: public synchronized void add(int value) { this.count += value; } SynchronizationMethodDemo

28 SynchronizationBlockDemo
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

29 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.

30 Wait-Notify Mechanism
notify( ) wakes up or notifies the first thread. notify( )‏ First thread notifyAll( ) wakes up or notifies all the threads that called wait( ) on the same object. Thread 1 Thread 2 Thread 3 notifyAll( )‏ JoinDemo InterThreadCommDemo(Producer Consumer.java)

31 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: It is important to remember that ‘threads running in parallel’ does not 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.

32 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

33 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.

34 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 { }

35 2. Implementing the run() Method
public void run() { } Thread Code Here 3. Starting New Thread MyThread aThread = new MyThread(); aThread.start(); //Invoke run() method

36 Creating threads using the thread class
class A 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 "); class B extends Thread for(int j = 1;j <= 5;j++) System.out.println("\tFrom Thread B : j = " + j); System.out.println("Exit from B ");

37 class C extends Thread { 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 ThreadTest public static void main(String args[]) A a = new A(); B b = new B(); C c = new C(); a.start(); b.start(); c.start();

38 IMPLEMENTING THE ‘RUNNABLE’ INTERFACE
The Runnable interface declares the run() method that is required for implementing threads in our programs. To do this, we must perform the steps listed below: 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.

39 import java.lang.Thread;
class X implements Runnable { public void run() for(int i = 1;i <= 5;i++) System.out.println("\tFrom Thread A : i = " + i); } System.out.println("Exit from A "); class Y implements Runnable for(int j = 1;j <= 5;j++) System.out.println("\tFrom Thread B : j = " + j); System.out.println("Exit from B ");

40 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();

41 LIFE CYCLE OF A THREAD During the life time of a thread, there are many states it can enter. They include Newborn state Runnable state Running state Blocked state Dead state

42 State Transition diagram of a Thread
Newborn New Thread start stop Active Thread stop Runnable Dead Running yield Killed Thread suspend sleep wait resume notify stop Blocked Idle Thread (Not Runnable)

43 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

44 Runnable State The runnable state means that the thread is ready for execution and is waiting for the availability of processor. That is, the thread has joined the queue of threads that are waiting for execution. 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. 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. 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() Running Thread

45 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

46 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

47 Blocked State 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 A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead therefore fully qualified to run again.

48 Dead State Every thread has life cycle. A running thread ends its life when it has completed executing its run() method. 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. A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable” (blocked) condition.

49 import java.lang.Thread;
class A 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 "); class B extends Thread 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 ");

50 class C extends Thread { public void run() for(int k = 1;k <= 5;k++) System.out.println("\tFrom Thread C : k = " + k); if(k==1) try sleep(1000); } catch(Exception e) System.out.println("Exit from C "); class ThreadTest_1 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");

51 final boolean isAlive() final void join() throws InterruptedException
Using isAlive() and join() isAlive() Two ways exist to determine whether a thread has finished. First, you can call isAlive() on the thread. The method is defined by Thread, and its general form is shown here: final boolean isAlive() The isAlive() method returns true if the thread upon which it is called is still running. It returns false otherwise. join While isAlive() is occasinally useful, the method that you will more commonly use to wait for a thread to finish is called join(), shown here: final void join() throws InterruptedException This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it.

52 class A 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 "); class B extends Thread for(int j = 1;j <= 5;j++) System.out.println("\tFrom Thread B : j = " + j); System.out.println("Exit from B ");

53 class C extends Thread { 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 ThreadTest public static void main(String args[]) A a = new A(); B b = new B(); C c = new C();

54 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"); System.out.println("Thread One is Alive: " + a.isAlive()); System.out.println("Thread two is Alive: " + b.isAlive()); System.out.println("Thread three is Alive: " + c.isAlive()); try { a.join(); b.join(); c.join(); } catch(InterruptedException e) System.out.println("Main Thread Interrupted");

55 ThreadName.setPriority(intNumber);
THREAD PRIORITY In java, each thread is assigned a prioriy, which affects the order in which it is scheduled for running. The threads of the same priority are given equal treatment by the Java scheduler and, therefore, they share the processor of a first – come, first – serve basis. ThreadName.setPriority(intNumber); The intNumber is an integer value to which the thread’s priority is set. The Thread class defines several priority constants: MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10 The intNumber may assume one of these constants or any value between 1 and 10. Note that the default setting is NORM_PRIORITY

56 import java.lang.Thread;
class A 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 "); class B extends Thread for(int j = 1;j <= 5;j++) System.out.println("\tFrom Thread B : j = " + j); System.out.println("Exit from B ");

57 class C extends Thread { 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 ThreadPriority public static void main(String args[]) A a = new A(); B b = new B(); C c = new C(); c.setPriority(5); //c.setPriority(NORM_PRIORITY); b.setPriority(10); //b.setPriority(MAX_PRIORITY); a.setPriority(1); //a.setPriority(MIN_PRIORITY); a.start(); b.start(); c.start();


Download ppt "THREAD MODEL."

Similar presentations


Ads by Google