Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
Use of multithreading is preferred rather than multiprocessing because threads share a
common memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Advantage of Java Multithreading
It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
Perform many operations together so it saves time.
Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously to utilize the CPU.
Multitasking can be achieved by two ways:
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
Process based multitasking allows the computer to run one or more programs
simulataneously.
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.
2) Thread-based Multitasking (Multithreading)
Thread based multitasking allows the computer to run one or more threads of the same
program simultaneously.
Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.
Switching between threads is of lower cost.
Thread in java
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path
of execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
As shown in the above 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.
Life cycle of a Thread
A thread can be in one of the five states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
When a new Thread object using new operator is created, the thread state is New Thread.
At this point, thread is not alive and it’s a state internal to Java programming.
2. Runnable
When start() function on Thread object is invoked, it’s state is changed to Runnable
The control is given to Thread scheduler to finish it’s execution.
Whether to run this thread instantly or keep it in runnable thread pool before running it
depends on the OS implementation of thread scheduler.
3. Running
When thread is executing, it’s state is changed to Running.
Thread scheduler picks one of the thread from the runnable thread pool and change it’s
state to Running and CPU starts executing this thread.
A thread can change state to Runnable, Dead or Blocked from running state depends on
time slicing, thread completion of run() method or waiting for some resources.
4. Blocked/Waiting
A thread can be waiting for other thread to finish using thread join or it can be waiting for
some resources to available
for example producer consumer problem or dining philosophers implementation or IO
resources, then it’s state is changed to Waiting.
Once the thread wait state is over, it’s state is changed to Runnable and it’s moved back
to runnable thread pool.
5. Dead / Terminated
Once the thread finished executing, it’s state is changed to Dead and it’s considered to be
not alive.
Thread Scheduler
Thread scheduler in java is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.
Creating Threads
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the [Link] calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public [Link] getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.
Example:
class Multi extends Thread
{
public void run()
{
[Link]("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
[Link]();
}
}
Output
thread is running…
Thread class constructor allocates a new thread object. When object of Multi class is created,
the Multi class constructor is invoked(provided by Compiler) fromwhere Thread class
constructor is invoked(by super() as first statement). Hence, Multi class object is thread object
now.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
1. A new thread starts(with new callstack).
2. The thread moves from New state to the Runnable state.
3. When the thread gets a chance to execute, its target run() method will run.
class Multi implements Runnable
{
public void run()
{
[Link]("thread is running...");
}
public static void main(String args[])
{
Multi m1=new Multi();
Thread t1=new Thread(m1);
[Link]();
}
}
Output
thread is running…
If the Thread class is not extended, then the class object would not be treated as a thread object. So
explicitly create Thread class object. and pass the object of the class that implements Runnable so that
your class run() method may execute.
Sleep method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
The Thread class provides two methods for sleeping a thread:
public static void sleep(long miliseconds)throws InterruptedException
public static void sleep(long miliseconds, int nanos)throws InterruptedException
class TestSleepMethod1 extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
try
{
[Link](500);
}
catch(InterruptedException e){[Link](e);}
[Link](i);
}
}
public static void main(String args[])
{
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
[Link]();
[Link]();
} }
Priority of a Thread
Java assigns to each thread a priority that determines how that thread should be treated
with respect to other threads
Priorities are represented by a number between 1 and 10.
In most cases, thread schedular schedules the threads according to their priority (known
as preemptive scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses.
Thread priority decides when to switch from one running thread to next thread
Context switching is simple when
Thread can voluntarily relinquish control
Threads can be preempted by higher-priority thread.
When two threads have same priority compete for CPU cycles.
3 constants defiend in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. 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.
class TestMultiPriority1 extends Thread
{
public void run()
{
[Link]("thread name is:"+[Link]().getName());
[Link]("thread priority is:"+[Link]().getPriority());
}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}