2. Thread
* A thread is a lightweight sub process, a smallest
unit of processing.
* It is a separate path of execution.
Class ABC
{
-----------
-----------
-----------
-----------
-----------
-----------
-----------
-----------
}
Beginning
Single-threaded body
of execution
End
Fig 1: Single-threaded Program
3. * Threads are independent, if there occurs exception
in one thread, it doesn't affect other threads.
* It shares a common memory area.
t2
t3
t1
Process 1
Process 2
Process 3
t1
t2
t1
Fig 2 : OS
4. Figure, thread is executed inside the process. There is
context-switching between the threads.
There can be multiple processes inside the OS and one
process can have multiple threads.
Java Thread Class :
* Thread class is the main class on which java's
multithreading system is based.
* Thread class provide constructors and methods to
create and perform operations on a thread.
* Thread class extends Object class and implements
Runnable interface.
5. Multithreading :
* Multithreading in java is a process of executing
multiple threads simultaneously.
* Thread is a sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve
multitasking.
* A separate memory area to saves memory, and context-
switching between the threads takes less time than process.
Advantages :
1) It doesn't block the user because threads are
independent and perform multiple operations at 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 exception occur in a single thread.
6. Main Thread
Thread A Thread B Thread C
Start Start Start
Main Method
Module
Switching Switching
Fig 3 :
Multithreaded Program
7. Multitasking
* Multitasking is a process of executing multiple tasks
simultaneously. We use multitasking to utilize the CPU.
* Multitasking can be achieved by two ways:
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
* Each process have its own address in memory i.e. each
process allocates separate memory area.
* Process is heavyweight.
* Cost of communication between the process is high.
* Switching from one process to another require some
time for saving and loading registers, memory maps, updating
lists etc.
8. 2) Thread-based Multitasking (Multithreading)
* Threads share the same address space.
* Thread is lightweight.
* Cost of communication between the thread is low.
Java Thread Method
Methods
start() getName() destroy()
run() setName() interrupt()
sleep() getId() isinterrupt()
currentThread() yield() notify()
join() suspend() toString()
getPriority() resume() notifyAll()
setPriority() stop() enumerate()
9. Difference between multithreading and multitasking
Multithreading Multitasking
1. It is a programming concept in which a
program or a process is divided into two
or more subprogram or threads that are
executed at the same time in parallel.
1. It is an operating system concept in
which multiple tasks are performed
simultaneously.
2. It supports execution of multiple parts
of a single program simultaneously.
2. It supports execution of multiple
programs simultaneously.
3. The processor has to switch between
different parts or threads of a program.
3. The processor has to switch between
different programs or processes.
4. It is highly efficient. 4. It is less efficient in comparison to
multithreading.
5. A threads is the smallest unit in
multithreading.
5. A program or process is the smallest
unit in a multitasking environment.
6. It helps in developing efficient
programs.
6. It helps in developing efficient
operating system.
7. It is cost-effective in case of context
switching.
7. It is expensive in case of context
switching.
10. Life cycle of Thread
* During the life cycle of thread, there are many state of
thread.
They include:
1. Newborn State.
2. Runnable State.
3. Running State.
4. Blocked State (Non-Runnable).
5. Dead State (Terminated).
* There is only 4 states in thread life cycle in java new,
runnable , non-runnable and terminated.
* There is no running state.
* But for better understanding the threads, we are
explaining it in the 5 states.
*The life cycle of the thread in java is controlled by JVM.
12. 1) New
The thread is in new state if you create an instance of
Thread class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be the
running thread.
Newborn
Dead State
Runnable
State
13. 3) Running
The thread is in running state if the thread scheduler
has selected it.
i) Suspend() – resume()
ii) Sleep() – Suspend()
iii) Wait() – Notify()
14. 4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is
currently not eligible to run.
5) Terminated (Dead)
A thread is in terminated or dead state when its run()
method exits.
How to create thread :
There are two ways to create a thread.
1. By extending Thread class
2. By implementing Runnable interface.
15. Extending Thread Class :
1. Declare the class and 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. Declare the class 2. Implement the
run()
3. Start New thread
class mythread extends
Thread
{
-------------------
-------------------
-------------------
}
public void run()
{
------------------
------------------
------------------
------------------
}
mythread athread=new
mythread();
athread.start();
16. Implementing Runnable Interface :
1. Declare the class as implementing the Runnable
interface.
2. Implement the run() method.
3. Create a thread by defining an object that is
instantiated from this “runnable” class as the target of the thread.
4. Call the thread’s start() method to run the thread.
Synchronization :
* Java enable us to overcome the problem using a
technique known as synchronization.
* It is a keyword synchronization.
* The method that will read information from a file and
the method that will update the same file may be declared as
synchronized.
17. Runnable Interface
class x implements Runnable
(
public void run()
{
for(int i=1;i<10,i++)
{
System.out.println(“t Thread:”+i);
}
}
class runnabletest
{
public static void main(String args[ ])
{
x runnable=new x();
Thread threadx=new Thread(runnable);
threadx.start( );
System.out.println(“End of main thread”);
}
}
Output
End of main thread
Thread : 1
Thread : 2
Thread : 3
Thread : 4
Thread : 5
Thread : 6
Thread : 7
Thread : 8
Thread : 9
Thread : 10
End of thread
Program 1:
Runnable Interface
18. Priority of a Thread (Thread Priority) :
* Each thread have a priority. Priorities are represented
by a number between 1 and 10.
* Thread scheduler schedules the threads according to
priority (known as preemptive scheduling).
* But it is not guaranteed because it depends on JVM
specification that which scheduling.
3 constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
* Default priority of a thread is 5 (NORM_PRIORITY).
* The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
19. Example of Priority of a Thread
class TestMultiPriority1 extends Thread
{
public void run() {
System.out.println("running thread name is:“
+Thread.currentThread().getName());
System.out.println("running thread priority is:“
+Thread.currentThread().getPriority()); }
public static void main(String args[]) {
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority( Thread. MIN_PRIORITY);
m2.setPriority( Thread. MAX_PRIORITY);
m1.start();
m2.start(); }
}
Thread Priority Output
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1