multithreading,thread and processinjava-210302183809.pptx

ArunPatrick2 20 views 37 slides Aug 29, 2024
Slide 1
Slide 1 of 37
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37

About This Presentation

java


Slide Content

Multithreading in Java Mrs.R.Hannah Roseline Assistant Professor ,

Introduction The program in execution is called " Process ". The program can be structured as set of individual units that can run in parallel. These units can be called as " Threads ". Multiprogramming is actually a kind of multitasking. The multitasking is either process-based or thread base. Process-based multitasking is nothing but, execution of more than one program concurrently. Thread-based multitasking allows more than one thread within the program run simultaneously or concurrently. The process is a Heavy Weight Process. The Thread is a Light Weight Process.

The context-switching of CPU from one process to other requires more overhead as it different address spaces are involved in it. On the other hand, context-switching is less overhead because of all the threads within the same program. The objective of all forms of the Multitasking including the multithreading is to utilize the idle time of the processor. From here onwards, thread-based multitasking is called " Multithreading ".

Multithreading in  Java. MULTITHREADING  in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other. Mulitple threads don't allocate separate memory area, hence they save memory. Also, context switching between threads takes less time . Advantages of MULTITHREADING :   1) It   doesn't block the user  because threads are independent and you can perform multiple operations at the same time. 2) You  can perform many operations together, so it saves time . 3) Threads are  independent , so it doesn't affect other threads if an exception occurs in a single thread.

Multithreading in  Java. Every program that we have been writing has at least one thread, that is, the " main " thread. Whenever a program starts executing, the JVM is responsible for creating the main thread and calling " main() " method. Along with this main thread, some other threads are also running to carryout the tasks such as " finalization " and " garbage collection ". The thread can either die naturally or be forced to die. Thread dies naturally when it exits from the "run()" method. Thread can be forced to die by calling "interrupt()" method .

Multitasking. Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways : 1 ) Process-based Multitasking (Multiprocessing) Each process has an address in memory. In other words, each process allocates a separate memory area. A process is heavyweight. Cost of communication between the process is high. Switching from one process to another requires some time for saving and loading  registers , memory maps, updating lists, etc. 2) Thread-based Multitasking (Multithreading) Threads share the same address space. A thread is lightweight. Cost of communication between the thread is low.

Difference between Multiprocessing and Multithreading Process-Based Multitasking Thread-Based Multitasking This deals with "Big Picture" This deals with Details These are Heavyweight tasks These are Lightweight tasks Inter-process communication is expensive and limited Inter-Thread communication is inexpensive. Context switching from one process to another is costly in terms of memory Context switching is low cost in terms of memory, because they run on the same address space This is not under the control of Java This is controlled by Java

Life Cycle of a Thread

During the life time of the thread, there are many states it can enter. The life cycle of the thread in java is controlled by JVM. The java thread states are as follows : Newborn state(New state or start state) The thread is in new state if you create an instance of Thread class but before the invocation of start() method . At this state we can do the following: Schedule it for running using the start() method. Kill it using stop() method.

Runnable State: A runnable state means that a thread is ready for execution and waiting for the availability of the processor . That is the thread has joined the queue of the threads for execution. If all the threads have equal priority, then they are given time slots for execution in the round rabin fashion , first-come first-serve manner. The thread that relinquishes the control will join the queue at the end and again waits for its turn. This is known as time slicing .

Running state : Running state means that the processor has given its time to the thread for it execution. The thread runs until it relinquishes the control or it is preempted by the other higher priority thread. As shown in the fig. a running thread can be preempted using the suspend(), or wait(), or sleep() methods. Blocked state: A thread is said to be in the blocked state when it is prevented from entering into runnable state and subsequently the running state. Dead state: Every thread has a life cycle. A running thread ends its life when it has completed execution. It is a natural death. However we also can kill the thread by sending the stop() message to it at any time.

How to create thread( java.lang.Thread package ) There are two ways to create a thread: By extending Thread class By implementing Runnable interface. Creation of Thread in java is very simple task. There is a class called "Thread", which belongs to the "java.lang.Thread" package. This package contains one interface also called "Runnable". Both these contain a common method called " run() " which is the heart of the thread. The run() methods would have the following syntax: Syntax : public void run() { // statement for implementing the thread. }

The methods of the Thread class are as follow : public void run():  is used to perform action for a thread. public void start():  starts the execution of the thread. JVM calls the run() method on the thread. public void sleep(long miliseconds ):  Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. public void join():  waits for a thread to die. public void join(long miliseconds ):  waits for a thread to die for the specified miliseconds . public int getPriority ():  returns the priority of the thread. public int setPriority ( int priority):  changes the priority of the thread. public String getName ():  returns the name of the thread. public void setName (String name):  changes the name of the thread. public Thread currentThread ():  returns the reference of currently executing

public int getId ():  returns the id of the thread. public Thread.State getState ():  returns the state of the thread. public boolean isAlive ():  tests if the thread is alive. public void yield():  causes the currently executing thread object to temporarily pause and allow other threads to execute. public void suspend():  is used to suspend the thread( depricated ). public void resume():  is used to resume the suspended thread( depricated ). public void stop():  is used to stop the thread( depricated ). public boolean isDaemon ():  tests if the thread is a daemon thread. public void setDaemon ( boolean b):  marks the thread as daemon or user thread. public void interrupt():  interrupts the thread. public boolean isInterrupted ():  tests if the thread has been interrupted. public static boolean interrupted():  tests if the current thread has been interrupted. notif ()- is calls the thread that is waiting for resource notifyAll ()-is calls the all threads that are waiting for resource

Thread Constructors Thread class: Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface . Commonly used Constructors of Thread class: Thread () -without arguments, default constructor Thread(String str ) - Thread contains name given as argument Thread(Thread obj , String str ) - takes thread object and string Thread(class Obj ) – takes the runnable class as target object Thread class:

The Main Thread Every java program has a thread called "main" thread. When the program execution starts, the JVM creates "main" Thread and calls the "main()" method from within that thread. Along with this JVM also creates other threads for the purpose of the Housekeeping task such as "garbage" collection. The "main" thread Spawns the other Threads. These spawned threads are called " Child Threads" . The main thread is always is the last thread to finish execution. We, as Programmer can also take control of the main thread, using the method " currentThread () ". The main thread can be controlled by this method. We can also change the name of the Thread using the method " setName (String name ) ".

Example Program. class MainThread { public static void main(String args []) { Thread t= Thread.currentThread (); System.out.println ("Name of the Thread is:"+t); t.setName (“AIMS ECE 2 nd YEAR STUDENTS"); System.out.println ("Name of the Thread is:"+t); } }

The Thread Priorities To set a thread’s priority, use the setPriority ( ) method, which is a member of Thread . This is its general form:   final void setPriority ( int level )  Here, level specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY . Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY , which is currently 5. These priorities are defined as static final variables within Thread . You can obtain the current priority setting by calling the getPriority ( ) method of Thread , shown here : final int getPriority ( )

setPriority () and getpriority () method using. class PTest {     public static void main(String args [])     {     //setting the priorities to the thread using the setPriority () method     PThread1 pt1=new PThread1();         pt1.setPriority(1);         PThread2 pt2=new PThread2();             pt2.setPriority(9);             PThread3 pt3=new PThread3();                 pt3.setPriority(6);             pt1.start();             pt2.start();             pt3.start(); //getting the priority System.out.println ("The pt1 thread priority is :"+pt1.getPriority());     } }

Runnable interface in Java Runnable interface in Java: The   Runnable interface  should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run . This  interface  is designed to provide a common protocol for objects that wish to execute code while they are active . Syntax: public void run() Steps involve in the Runnable interface in java: Create a  Runnable  implementer and implement  run () method. Instantiate   Thread class  and pass the implementer to the Thread , Thread has a constructor which accepts  Runnable  instance. Invoke start() of Thread instance, start internally calls  run () of the implementer .

Implementing Runnable Interface package aims ;   public class aims RunnableDemo {        public static void main(String[] args ) {          System.out.println ("From main() : " + Thread.currentThread (). getName ());            System.out.println ("Creating Runnable Instance...");         Runnable runnable = new Runnable() {             @Override              public void run() {                  System.out.println ("From run() : " + Thread.currentThread (). getName ());             }         };            System.out.println ("Creating a Thread Instance...");         Thread thread = new Thread(runnable);            System.out.println ("Launching a Thread...");          thread.start ();     } }

Output:- From main() : main Creating Runnable Instance... Creating a Thread Instance... Launching a Thread... From run() : Thread-

Synchronization in Java. When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization . Key to synchronization is the concept of the monitor (also called a semaphore ). A monitor is an object that is used as a mutually exclusive lock, or mutex . Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires .

Types of Synchronization: There are two types of synchronization Process Synchronization Thread Synchronization Process Synchronization On the basis of synchronization, processes are categorized as one of the following two types: Independent Process  : Execution of one process does not affects the execution of other processes. Cooperative Process  : Execution of one process affects the execution of other processes. Process synchronization problem arises in the case of Cooperative process also because resources are shared in Cooperative processes . Types of Synchronization in Java.

Thread Synchronization. Thread Synchronization There are two types of thread synchronization mutual exclusive and inter-thread communication . 1.Mutual Exclusive Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java: Synchronized method . Synchronized method  is used to lock an object for any shared resource. When a thread invokes a  synchronized method , it automatically acquires the lock for that object and releases it when the thread completes its task . Synchronized method  is used to lock an object for any shared resource. When a thread invokes a  synchronized method , it automatically acquires the lock for that object and releases it when the thread completes its task .

Synchronized method . When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task. Example:- public class SynchronizedCounter { private int c = 0 ; public synchronized void increment() { c++ ; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } }

Synchronized block . Synchronized block . Synchronized block can be used to perform synchronization on any specific resource of the method . Syntax:- synchronized  (object reference expression) {       // code block    }   Points to remember for Synchronized block Synchronized block is used to lock an object for any shared resource. Scope of synchronized block is smaller than the method .

static synchronization . static synchronization. If you make any static method as synchronized, the lock will be on the class not on object . Problem without static synchronization: Suppose there are two objects of a shared class(e.g. Table)named object1 and object2.In case of synchronized method and synchronized block there cannot be interference betweent1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves this problem .

Inter-thread communication 2.Inter-thread communication Inter-thread communication  or  Co-operation  is all about allowing synchronized threads to communicate with each other . Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of  Object class : wait () notify() notifyAll () Note:- If two or more Threads are communicating with each other, it is called " inter thread " communication. Using the synchronized method, two or more threads can communicate indirectly.

wait () method . 1.wait () method:- Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll () method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception. Method Description public final void wait()throws InterruptedException waits until object is notified. public final void wait(long timeout)throws InterruptedException waits for the specified amount of time.

notify() and notify All() method. 2.notify () method:- Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax: public final void notify () 3.notifyAll () method:- Wakes up all threads that are waiting on this object's monitor. Syntax: public final void notifyAll ()

process of inter-thread communication. Understanding the process of inter-thread communication:- The point to point explanation of the above diagram is as follows : Threads enter to acquire lock. Lock is acquired by on thread. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. If you call notify() or notifyAll () method, thread moves to the notified state (runnable state). Now thread is available to acquire lock. After completion of the task, thread releases the lock and exits the monitor state of the object .

Difference between wait and sleep. wait() sleep() wait() method releases the lock sleep() method doesn't release the lock. is the method of Object class is the method of Thread class is the non-static method is the static method is the non-static method is the static method should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is completed.

Example of inter thread communication in java class  Customer{   int  amount=10000;     synchronized   void  withdraw( int  amount){   System.out.println ("going to withdraw...");     if ( this .amount <amount ){   System.out.println ("Less balance; waiting for deposit...");   try {wait();} catch (Exception e){}   }   this .amount -=amount;   System.out.println ("withdraw completed...");   }     synchronized   void  deposit( int  amount){   System.out.println ("going to deposit...");   this .amount +=amount;   System.out.println ("deposit completed... ");   notify();   }   }     class  Test{   public   static   void  main(String  args []){   final  Customer c= new  Customer();   new  Thread(){   public   void  run(){ c.withdraw (15000);}   }.start();   new  Thread(){   public   void  run(){ c.deposit (10000);}   }.start();      }}  

Interrupting a Thread Interrupting a Thread: If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException . If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true . There are 3 methods provide in Thread class for thread interruption. public void interrupt() public static boolean interrupted() public boolean isInterrupted ()

Thread Exceptions Note that a call to the sleep() method is always enclosed in try/ catch block. . it general form will be as follows: try { Thread.sleep (1000); } cathc (Exception e) { ------- --------- }

Disadvantages of Synchronization This way of communications between the threads competing for same resource is called implicit communication . This has one disadvantage due to polling. The polling wastes the CPU time. To save the CPU time, it is preferred to go to the inter-thread communication (explicit communication ) .
Tags