Multithreading PRESENTED BY –: Kartik dube (008)
What is a Process?
 Process is a isolated, independently executing programs to which OS allocate resources such as memory, file handlers, security credentials, etc.  Processes communicate with one another through mechanisms like sockets, signal handlers, shared memory, semaphores and files.
What is Thread?
 Threads are called lightweight processes.  Threads are parts of Processes. So all the threads created by one particular process can share the process's resources (memory, file handlers, etc).  There may be several threads in one process  Threads are independent because they all have separate path of execution that’s the reason if an exception occurs in one thread, it doesn’t affect the execution of other threads.
Process vs threads
What is Multithreading ?  The process of executing multiple threads simultaneously is known as multithreading.
Before we talk about multithreading, Back in the old days a computer had a single CPU, and was only capable of executing a single program at a time. Later came multitasking which meant that computers could execute multiple programs (processes) at the same time. . The single CPU was shared between the programs. The operating system would switch between the programs running, executing each of them for a little while before switching. Later yet came multithreading which mean that you could have multiple threads of execution inside the same program.
Multithreading can be a great way to increase the performance of some types of programs. Multithreading extends the idea of multitasking into applications, so you can subdivide specific operations within a single application into individual Threads. Each of the threads can run in parallel. For example, one subprogram can display an animation on the screen while another may build the next animation to be displayed. Since all the threads are running on a single processor, the flow of execution is shared between the threads. The java interpreter handles the switching of control between the threads in such a way that it appears they are running concurrently.
A Thread is a basic unit of CPU utilization, consisting of a program counter, a stack, and a set of registers, ( and a thread ID. ) Traditional ( heavyweight ) processes have a single thread of control - There is one program counter, and one sequence of instructions that can be carried out at any given time. As shown in Figure , multi-threaded applications have multiple threads within a single process, each having their own program counter, stack and set of registers, but sharing common code, data, and certain structures such as open files.
Figure - Single-threaded and multithreaded processes
Life Cycle of 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
Life Cycle of Thread
1. Newborn State Thread t1 = new Thread(); In new born state, the thread object is just created but not started yet, we can say it is inactive. In the above statement t1 thread is created but not started. To make the thread active, call start() method on the thread object as t1.start(). This makes the thread active and now eligible to run, now it goes to runnable state.
2. Runnable state (start()) The runnable state means that the thread is ready for execution and is waiting for the availability of the processor.
2. Runnable state (start())  When the thread is active, the first and foremost job, it does is calling run() method.  When the thread is executing the run() method, we say, the thread is in runnable state.As it is a callback method, all the code expected to run by the thread, is written here. In this state, the thread is active.
3. Running State  Running means that the processor has given its time to the thread for its execution.  A running thread may relinquish its control in one of the following situations:
1. Suspend() and resume() Methods:- This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it. Running Runnable Suspended suspended resume
2. Sleep() Method :- This means that the thread is out of the queue during this time period. The thread re-enter the runnable state as soon as this time period is elapsed. Running Runnable Sleeping sleep(t)
3. Wait() and notify() methods :- blocked until certain condition occurs Running Runnable Waiting wait notify
4. Blocked State  A thread is said to be blocked when it is prevented form 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.
5. Dead State  A running thread ends its life when is 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.
State diagram of a thread yield Newborn start stop stop stop suspended sleep wait resume notify Blocked Dead Running RunnableActive Thread New Thread Idle Thread (Not Runnable) Killed Thread
How to create thread  Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.  A new thread can be created in two ways:  By extending a thread class  By implementing an interface
Commonly used methods of Thread class: • 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 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 int getId(): returns the id of the thread. • 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. • public void resume(): is used to resume the suspended thread. • public void stop(): is used to stop the thread..
Create a Thread by Implementing a Runnable Interface Step 1 : As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method − public void run( ) { // }
Thread(Runnable threadObj); Where, threadObj is an instance of a class that implements the Runnable interface Step 2 : As a second step, you will instantiate a Thread object using the following constructor − Create a Thread by Implementing a Runnable Interface
Step 3 : Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Create a Thread by Implementing a Runnable Interface
class TDemo implements Runnable { public void run() { for(int i=0;i<=5;i++) { System.out.println("CONCURRENT THREAD RUNNING SIMUNTANIOUSLY......!!!.....:"+i); } } } class Main_TDemo1 { public static void main(String arg[]) { TDemo obj = new TDemo(); Thread t = new Thread(obj); t.start(); } } Example
Output :
Create a Thread by Extending the Thread class  We can directly extend the Thread class  The class TDemo extends Thread. The logic for the thread is contained in the run() method.
class TDemo extends Thread { public void run() { for(int i=0;i<=5;i++) { System.out.println("CONCURRENT THREAD RUNNING SIMUNTANIOUSLY......!!!.....:"+i); } } } class Main_TDemo1 { public static void main(String arg[]) { TDemo obj = new TDemo(); obj.start(); } } Example
Output :
Synchronization  When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues.  For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file.
 Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block synchronized (object) { //statement to be synchronized } Synchronization
Why use Synchronization The synchronization is mainly used to :- • To prevent thread interference. • To prevent consistency problem.
class MDemo { public static void main(String arg[])throws InterruptedException { SDemo obj = new SDemo(); Thread t1 = new Thread(obj); Thread t2 = new Thread(obj); t1.start(); t2.start(); } }
class SDemo implements Runnable { int avail = 1; int req = 1; public void run() { System.out.println("AVAILABLE BIRTH = "+avail); synchronized(this) { if(avail >= req) { System.out.println("1 BIRTH IS RESERVED"); try { Thread.sleep(2000); avail = avail-req; } catch(Exception e){} } else System.out.println("RECENTLY NO BIRTH AVAILABLE "); } } }
Thank You..!!

Multithreading Introduction and Lifecyle of thread

  • 1.
  • 2.
    What is aProcess?
  • 3.
     Process isa isolated, independently executing programs to which OS allocate resources such as memory, file handlers, security credentials, etc.  Processes communicate with one another through mechanisms like sockets, signal handlers, shared memory, semaphores and files.
  • 4.
  • 5.
     Threads arecalled lightweight processes.  Threads are parts of Processes. So all the threads created by one particular process can share the process's resources (memory, file handlers, etc).  There may be several threads in one process  Threads are independent because they all have separate path of execution that’s the reason if an exception occurs in one thread, it doesn’t affect the execution of other threads.
  • 6.
  • 7.
    What is Multithreading?  The process of executing multiple threads simultaneously is known as multithreading.
  • 8.
    Before we talkabout multithreading, Back in the old days a computer had a single CPU, and was only capable of executing a single program at a time. Later came multitasking which meant that computers could execute multiple programs (processes) at the same time. . The single CPU was shared between the programs. The operating system would switch between the programs running, executing each of them for a little while before switching. Later yet came multithreading which mean that you could have multiple threads of execution inside the same program.
  • 9.
    Multithreading can bea great way to increase the performance of some types of programs. Multithreading extends the idea of multitasking into applications, so you can subdivide specific operations within a single application into individual Threads. Each of the threads can run in parallel. For example, one subprogram can display an animation on the screen while another may build the next animation to be displayed. Since all the threads are running on a single processor, the flow of execution is shared between the threads. The java interpreter handles the switching of control between the threads in such a way that it appears they are running concurrently.
  • 10.
    A Thread isa basic unit of CPU utilization, consisting of a program counter, a stack, and a set of registers, ( and a thread ID. ) Traditional ( heavyweight ) processes have a single thread of control - There is one program counter, and one sequence of instructions that can be carried out at any given time. As shown in Figure , multi-threaded applications have multiple threads within a single process, each having their own program counter, stack and set of registers, but sharing common code, data, and certain structures such as open files.
  • 11.
    Figure - Single-threadedand multithreaded processes
  • 12.
    Life Cycle ofThread  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
  • 13.
  • 14.
    1. Newborn State Threadt1 = new Thread(); In new born state, the thread object is just created but not started yet, we can say it is inactive. In the above statement t1 thread is created but not started. To make the thread active, call start() method on the thread object as t1.start(). This makes the thread active and now eligible to run, now it goes to runnable state.
  • 15.
    2. Runnable state(start()) The runnable state means that the thread is ready for execution and is waiting for the availability of the processor.
  • 16.
    2. Runnable state(start())  When the thread is active, the first and foremost job, it does is calling run() method.  When the thread is executing the run() method, we say, the thread is in runnable state.As it is a callback method, all the code expected to run by the thread, is written here. In this state, the thread is active.
  • 17.
    3. Running State Running means that the processor has given its time to the thread for its execution.  A running thread may relinquish its control in one of the following situations:
  • 18.
    1. Suspend() andresume() Methods:- This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it. Running Runnable Suspended suspended resume
  • 19.
    2. Sleep() Method:- This means that the thread is out of the queue during this time period. The thread re-enter the runnable state as soon as this time period is elapsed. Running Runnable Sleeping sleep(t)
  • 20.
    3. Wait() andnotify() methods :- blocked until certain condition occurs Running Runnable Waiting wait notify
  • 21.
    4. Blocked State A thread is said to be blocked when it is prevented form 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.
  • 22.
    5. Dead State A running thread ends its life when is 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.
  • 23.
    State diagram ofa thread yield Newborn start stop stop stop suspended sleep wait resume notify Blocked Dead Running RunnableActive Thread New Thread Idle Thread (Not Runnable) Killed Thread
  • 24.
    How to createthread  Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.  A new thread can be created in two ways:  By extending a thread class  By implementing an interface
  • 25.
    Commonly used methodsof Thread class: • 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 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 int getId(): returns the id of the thread. • 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. • public void resume(): is used to resume the suspended thread. • public void stop(): is used to stop the thread..
  • 26.
    Create a Threadby Implementing a Runnable Interface Step 1 : As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method − public void run( ) { // }
  • 27.
    Thread(Runnable threadObj); Where, threadObjis an instance of a class that implements the Runnable interface Step 2 : As a second step, you will instantiate a Thread object using the following constructor − Create a Thread by Implementing a Runnable Interface
  • 28.
    Step 3 : Oncea Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Create a Thread by Implementing a Runnable Interface
  • 29.
    class TDemo implementsRunnable { public void run() { for(int i=0;i<=5;i++) { System.out.println("CONCURRENT THREAD RUNNING SIMUNTANIOUSLY......!!!.....:"+i); } } } class Main_TDemo1 { public static void main(String arg[]) { TDemo obj = new TDemo(); Thread t = new Thread(obj); t.start(); } } Example
  • 30.
  • 31.
    Create a Threadby Extending the Thread class  We can directly extend the Thread class  The class TDemo extends Thread. The logic for the thread is contained in the run() method.
  • 32.
    class TDemo extendsThread { public void run() { for(int i=0;i<=5;i++) { System.out.println("CONCURRENT THREAD RUNNING SIMUNTANIOUSLY......!!!.....:"+i); } } } class Main_TDemo1 { public static void main(String arg[]) { TDemo obj = new TDemo(); obj.start(); } } Example
  • 33.
  • 34.
    Synchronization  When westart two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues.  For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file.
  • 35.
     Java programminglanguage provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block synchronized (object) { //statement to be synchronized } Synchronization
  • 36.
    Why use Synchronization Thesynchronization is mainly used to :- • To prevent thread interference. • To prevent consistency problem.
  • 37.
    class MDemo { public staticvoid main(String arg[])throws InterruptedException { SDemo obj = new SDemo(); Thread t1 = new Thread(obj); Thread t2 = new Thread(obj); t1.start(); t2.start(); } }
  • 38.
    class SDemo implementsRunnable { int avail = 1; int req = 1; public void run() { System.out.println("AVAILABLE BIRTH = "+avail); synchronized(this) { if(avail >= req) { System.out.println("1 BIRTH IS RESERVED"); try { Thread.sleep(2000); avail = avail-req; } catch(Exception e){} } else System.out.println("RECENTLY NO BIRTH AVAILABLE "); } } }
  • 39.