MULTITHREADED
PROGRAMING.
Bharath S S
CSE(Cyber security).
What are Threads?
Thread is a Tiny program running continuously. It is
sometimes called as light-weight process. But there
lies differences between thread and process
Why Use Threads in Java?
A thread is the smallest unit of execution in a
program. In Java, threads allow us to run multiple
parts of a program concurrently (at the same time),
which improves efficiency and performance.
Creating Threads: Thread Class vs. Runnable
Interface
Extending Thread Class Implementing Runnable Interface
Simplest way: create a class that extends [Link] More flexible: create a class that implements
and override its run() method. [Link] and its run() method. Pass it to a
Thread constructor.
class MyThread extends Thread { public void class MyRunnable implements Runnable { public
run() { // Task to perform }} void run() { // Task to perform }}
Then, new MyThread().start(); Then, new Thread(new MyRunnable()).start();
The Runnable interface is generally preferred as it allows your class to extend other classes, promoting better design.
The Thread Lifecycle:
New Runnable
Terminated Blocked
Advantages & Disadvantages of Threads.
Advantages. Disadvantages.
• Better CPU Utilization • Risk of Deadlock
• Threads keep the processor busy by performing multiple • If threads wait for each other’s resources, the program
tasks simultaneously. may freeze (deadlock situation).
• Faster Execution • Difficult Debugging & Testing
• Tasks can run in parallel, reducing execution time. • Bugs caused by improper thread handling (like race
• Resource Sharing conditions) are difficult to reproduce and fix.
• • Unpredictable Results
Threads of the same process share memory and
resources, making communication easier. • If not handled properly, multiple threads accessing shared
• Low Cost resources can cause inconsistent or wrong results.
• Creating and switching between threads is cheaper than
processes.
Thank You!