Javatpoint Multithreading
Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared
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.
Advantages of Java 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.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
o Each process has an address in memory. In other words, each process allocates a
separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.
Note: At least one process is required for each thread.
What is Thread in java
A thread is a lightweight subprocess, the 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 uses a shared memory area.
As shown in the above figure, a 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.
Note: At a time one thread is executed only.
Java Thread class
Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a thread. Thread
class extends Object class and implements Runnable interface.
Java Thread Methods
S.N. Modifier and Type Method Description
1) void start() It is used
execution
2) void run() It is used
a thread.
3) static void sleep() It sleeps
specified
4) static Thread currentThread() It returns
currently
object.
5) void join() It waits fo
6) int getPriority() It returns
thread.
7) void setPriority() It change
thread.
8) String getName() It returns
thread.
9) void setName() It change
thread.
10) long getId() It returns
thread.
11) boolean isAlive() It tests if
12) static void yield() It causes
executing
pause an
threads t
temporar
13) void suspend() It is used
thread.
14) void resume() It is used
suspende
15) void stop() It is used
16) void destroy() It is used
thread gr
subgroup
17) boolean isDaemon() It tests if
daemon t
18) void setDaemon() It marks
daemon o
19) void interrupt() It interru
20) boolean isinterrupted() It tests w
has been
21) static boolean interrupted() It tests w
thread ha
22) static int activeCount() It returns
active thr
thread's t
23) void checkAccess() It determ
running t
permissio
thread.
24) static boolean holdLock() It returns
the curre
monitor l
object.
25) static void dumpStack() It is used
trace of t
the stand
26) StackTraceElement[] getStackTrace() It returns
trace elem
the stack
27) static int enumerate() It is used
active thr
and its su
specified
28) Thread.State getState() It is used
of the thr
29) ThreadGroup getThreadGroup() It is used
group to
belongs
30) String toString() It is used
represent
including
priority, a
31) void notify() It is used
notificatio
thread wh
particular
32) void notifyAll() It is used
notificatio
threads o
33) void setContextClassLoader() It sets th
ClassLoad
34) ClassLoader getContextClassLoader() It returns
ClassLoad
35) static getDefaultUncaughtExceptionHandler( It returns
Thread.UncaughtExceptionHandler ) invoked w
abruptly
uncaught
36) static void setDefaultUncaughtExceptionHandler() It sets th
invoked w
abruptly
uncaught
Do You Know
o How to perform two tasks by two threads?
o How to perform multithreading by anonymous class?
o What is the Thread Scheduler and what is the difference between preemptive
scheduling and time slicing?
o What happens if we start a thread twice?
o What happens if we call the run() method instead of start() method?
o What is the purpose of join method?
o Why JVM terminates the daemon thread if no user threads are remaining?
o What is the shutdown hook?
o What is garbage collection?
o What is the purpose of finalize() method?
o What does the gc() method?
o What is synchronization and why use synchronization?
o What is the difference between synchronized method and synchronized block?
o What are the two ways to perform static synchronization?
o What is deadlock and when it can occur?
o What is interthread-communication or cooperation?
What will we learn in Multithreading
o Multithreading
o Life Cycle of a Thread
o Two ways to create a Thread
o How to perform multiple tasks by multiple threads
o Thread Scheduler
o Sleeping a thread
o Can we start a thread twice?
o What happens if we call the run() method instead of start() method?
o Joining a thread
o Naming a thread
o Priority of a thread
o Daemon Thread
o ShutdownHook
o Garbage collection
o Synchronization with synchronized method
o Synchronized block
o Static synchronization
o Deadlock
o Inter-thread communication
Life cycle of a Thread (Thread States)
1. Life cycle of a thread
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in
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. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() m
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.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
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.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread cla
class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o 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 thread.JVM calls the run() method on the thread
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (tempora
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 Thread.State 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
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.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be execute
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:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
1) Java Thread Example by extending Thread class
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }
Output:thread is running...
2) Java Thread Example by implementing Runnable interface
1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11. }
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread object.So y
create Thread class object.We are passing the object of your class that implements Runnable so that yo
may execute.
Thread Scheduler in Java
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.
Difference between preemptive scheduling and time
slicing
Under preemptive scheduling, the highest priority task executes until it enters the waiting or
dead states or a higher priority task comes into existence. Under time slicing, a task
executes for a predefined slice of time and then reenters the pool of ready tasks. The
scheduler then determines which task should execute next, based on priority and other
factors.
Sleep method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount of
time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
o public static void sleep(long miliseconds)throws InterruptedException
o public static void sleep(long miliseconds, int nanos)throws InterruptedException
Example of sleep method in java
1. class TestSleepMethod1 extends Thread{
2. public void run(){
3. for(int i=1;i<5;i++){
4. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
5. System.out.println(i);
6. }
7. }
8. public static void main(String args[]){
9. TestSleepMethod1 t1=new TestSleepMethod1();
10. TestSleepMethod1 t2=new TestSleepMethod1();
11.
12. t1.start();
13. t2.start();
14. }
15. }
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.
Can we start a thread twice
No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for second
time, it will throw exception.
Let's understand it by the example given below:
1. public class TestThreadTwice1 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestThreadTwice1 t1=new TestThreadTwice1();
7. t1.start();
8. t1.start();
9. }
10. }
Test it Now
running
Exception in thread "main" java.lang.IllegalThreadStateException
What if we call run() method directly instead
start() method?
o Each thread starts in a separate call stack.
o Invoking the run() method from main thread, the run() method goes onto the current call stack r
beginning of a new call stack.
1. class TestCallRun1 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestCallRun1 t1=new TestCallRun1();
7. t1.run();//fine, but does not start a separate call stack
8. }
9. }
Test it Now
Output:running...
Problem if you direct call run() method
1. class TestCallRun2 extends Thread{
2. public void run(){
3. for(int i=1;i<5;i++){
4. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
5. System.out.println(i);
6. }
7. }
8. public static void main(String args[]){
9. TestCallRun2 t1=new TestCallRun2();
10. TestCallRun2 t2=new TestCallRun2();
11.
12. t1.run();
13. t2.run();
14. }
15. }
Test it Now
Output:1
2
3
4
5
1
2
3
4
5
As you can see in the above program that there is no context-switching because here t1 and t2 will be t
object not thread object.