0% found this document useful (0 votes)
21 views10 pages

Multithreading in Java

The document explains the concepts of processes and threads in programming, highlighting their differences, life cycles, and the advantages of multithreading. It details how to create threads in Java using both the Thread class and the Runnable interface, along with practical examples demonstrating multithreading. Additionally, it covers thread coordination, parallelism, concurrency, and the benefits and drawbacks of using multithreading in applications.

Uploaded by

Nisha Rathi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views10 pages

Multithreading in Java

The document explains the concepts of processes and threads in programming, highlighting their differences, life cycles, and the advantages of multithreading. It details how to create threads in Java using both the Thread class and the Runnable interface, along with practical examples demonstrating multithreading. Additionally, it covers thread coordination, parallelism, concurrency, and the benefits and drawbacks of using multithreading in applications.

Uploaded by

Nisha Rathi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROCESS: (A process is a program in execution with its own memory.

)
A process is an independent program in execution.
Examples: Running Chrome, Running a Java program, Running MS Word.
Each process has:
 Its own memory (separate address space)
 Its own heap, stack, data, code
 Its own resources
 Own CPU registers
Processes do NOT share memory by default. That’s why process switching is slow.

THREAD : (A thread is a lightweight part of the process that shares memory.)


A thread is a lightweight, smaller unit of a process. A process may have one thread or multiple threads. All
threads in the same process SHARE:
 Heap memory
 Code section
 Open files
 Global variables
Each thread has its own:
 Stack
 Program counter
 Registers
Threads allow multiple tasks to run inside the same program simultaneously.

Process vs Thread
Process Thread
Heavyweight Lightweight
Slow switching Fast switching
Independent memory Shared memory
Communication is difficult Easy communication
Examples: Chrome, Word UI thread, worker thread

THREAD LIFE CYCLE (Java) : Threads have a life cycle: new → runnable → running → waiting → terminated.
A thread goes through the following states:
1. New : Thread object is created but not started.
Thread t = new Thread();
2. Runnable : start() is called, and thread is ready to run (waiting for CPU time).
[Link]();
3. Running: Thread is currently executing code.
4. Blocked / Waiting / Timed Waiting
Thread is temporarily inactive because:
 Waiting for I/O
 Calling sleep()
 Waiting for lock
 Waiting for other threads
5. Terminated: Thread completes execution or is killed.
THREAD COORDINATION : Threads must coordinate to avoid conflicts (race conditions).
Java provides several mechanisms:
1. join() : Makes one thread wait until another finishes.
[Link](); // wait for t1 to finish
2. sleep(): Pauses a thread.
[Link](1000);
3. yield() : Hints to the scheduler to give other threads a chance.
4. Synchronization: Used when multiple threads access shared data.
synchronized void deposit() { ... }
5. Inter-thread communication
Using:
 wait()
 notify()
 notifyAll()
Allows threads to communicate safely using shared data.

PARALLELISM : (Parallelism happens when multiple threads run at the same time on multiple CPU cores.)
Parallelism means Two or more threads executing at the SAME time on different CPU cores.
Example (4-core CPU):
Core 1 → Thread A
Core 2 → Thread B
Core 3 → Thread C
Core 4 → Thread D

 True parallel execution


Requires multi-core CPU
 High performance
 Parallelism is actual simultaneous execution.
CONCURRENCY : (Concurrency happens when threads take turns on a single CPU.)
Concurrency means Multiple threads taking turns on a CPU so fast that it appears they run simultaneously.
Example on a single-core CPU:
Thread A → 5ms
Thread B → 5ms
Thread A → 5ms
Thread B → 5ms

 Achieved by time slicing


 Not actually simultaneous
 Scheduled by OS

MULTITHREADING : (Multithreading allows a program to perform multiple tasks at the same time.)
Multithreading = Running multiple threads in the same process.
Goals:
 Better CPU utilization
 Faster execution
 Smooth UI responsiveness
 Background tasks

Multithreading in Java: Multithreading is the process of executing multiple threads (lightweight


subprocesses) concurrently within a single program. Each thread runs independently and shares the same
memory space of the program.
Java supports multithreading at the language level by providing:
 Thread class
 Runnable interface
 Thread lifecycle methods (start(), run(), sleep(), etc.)

Need for Multithreading: Multithreading is used to improve:


 Performance
 CPU utilization
 Responsiveness of programs
 Parallel execution of independent tasks
Examples:
 Games
 Animation
 Web servers
 Download managers
 Real-time systems

Advantages of Multithreading
Advantage Description
Faster execution Tasks run parallel
Better CPU use Idle CPU time is minimized
Efficient programs Resource sharing among threads
Improved responsiveness UI applications stay responsive
Disadvantages of Multithreading
Disadvantage Explanation
Debugging is difficult Parallel tasks are harder to track
Synchronization issues Race conditions may occur
More complexity Need careful management
Deadlocks Improper locking can freeze program

Ways to Create Threads in Java


Method 1: Extending Thread class : Override the run() method and call start().
Method 2: Implementing Runnable interface :Pass object to Thread class and call start().

Syntax
Extending Thread
class MyThread extends Thread
{
public void run() { // code to execute in thread }
}

MyThread t = new MyThread();


[Link]();

Implementing Runnable
class MyRunnable implements Runnable
{
public void run() { // code for thread }
}

Thread t = new Thread(new MyRunnable());


[Link]();
JAVA PRACTICAL – Multithreading using Extending Thread class

AIM
To write a Java program to demonstrate Multithreading by creating and executing multiple threads that run
concurrently.

THEORY
Multithreading is the capability of Java to run multiple threads (small units of execution) simultaneously.
Each thread runs independently but shares the same memory and resources of the program.
Java provides built-in support for multithreading through:
1. Thread Class
A thread can be created by extending the Thread class and overriding its run() method.
Execution begins when we call the start() method.
2. Runnable Interface
A thread can also be created by implementing the Runnable interface and passing the object to a Thread
instance.
Thread Lifecycle
A thread goes through the following states:
 New
 Runnable
 Running
 Blocked / Waiting
 Terminated
Advantages of Multithreading
 Efficient use of CPU
 Faster program execution
 Multiple tasks run in parallel
 Improved performance and responsiveness
Common Thread Methods
 start() — starts thread execution
 run() — defines thread logic
 sleep(ms) — pauses thread
 join() — waits for a thread to finish
 getPriority() — returns priority
PROGRAM
class Task1 extends Thread
{
public void run()
{
for (int i = 1; i <= 5; i++)
{ [Link]("Task 1 - Count: " + i);
try { [Link](500); }
catch (Exception e) { [Link](e); }
}
}
}
class Task2 extends Thread
{
public void run()
{
for (int i = 1; i <= 5; i++)
{
[Link]("Task 2 - Count: " + i);
try { [Link](700); }
catch (Exception e) { [Link](e); }
}
}
}
public class MultiThreadDemo
{
public static void main(String[] args)
{
Task1 t1 = new Task1(); // creating first thread
Task2 t2 = new Task2(); // creating second thread
[Link](); // start first thread
[Link](); // start second thread
}
}

OUTPUT
(Order may vary because threads run concurrently)
Task 1 - Count: 1
Task 2 - Count: 1
Task 1 - Count: 2
Task 2 - Count: 2
Task 1 - Count: 3
Task 1 - Count: 4
Task 2 - Count: 3
Task 1 - Count: 5
Task 2 - Count: 4
Task 2 - Count: 5
CONCLUSION
This practical demonstrates Java's multithreading feature, where two threads execute concurrently. Both
threads run independently but share CPU time efficiently. By extending the Thread class and using the run()
and start() methods, the program shows how multiple tasks can run in parallel. Multithreading enhances
program performance, improves responsiveness, and makes better use of system resources.
JAVA PRACTICAL – Multithreading using Runnable Interface

AIM
To write a Java program to demonstrate multithreading by creating threads using the Runnable interface,
passing the Runnable object to the Thread class, and invoking the start() method.

THEORY
Java supports multithreading in two ways:
1. Extending the Thread class
2. Implementing the Runnable interface (recommended)
Why Runnable Interface?
 Java supports single inheritance, so extending Thread restricts you from extending another class.
 Runnable allows separation between thread object and thread execution logic.
 Runnable-based threads are more flexible and commonly used.
Runnable Interface
The Runnable interface contains only one method:
public void run();
To create a thread:
1. Create a class that implements Runnable.
2. Override the run() method with the thread logic.
3. Create a Thread object and pass the Runnable object to its constructor.
4. Call the start() method to execute the thread.
Thread Creation Steps
Step 1: class MyClass implements Runnable
Step 2: Override run() method
Step 3: Create object → MyClass obj = new MyClass();
Step 4: Thread t = new Thread(obj);
Step 5: [Link]();
Advantages
 Supports multiple inheritance indirectly
 Better separation between task and thread
 More flexible and scalable
PROGRAM
class Task1 implements Runnable
{
public void run()
{
for (int i = 1; i <= 5; i++)
{
[Link]("Task 1 - Count: " + i);
try { [Link](500); }
catch (Exception e) { [Link](e); }
}
}
}

class Task2 implements Runnable


{
public void run()
{
for (int i = 1; i <= 5; i++)
{ [Link]("Task 2 - Count: " + i);
try { [Link](700); }
catch (Exception e) { [Link](e); }
}
}
}

public class RunnableDemo


{
public static void main(String[] args)
{
// Creating Runnable objects
Task1 obj1 = new Task1();
Task2 obj2 = new Task2();
// Creating Thread objects and passing Runnable objects
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
// Starting threads
[Link]();
[Link]();
}
}

OUTPUT
(Actual order varies—threads run concurrently)
Task 1 - Count: 1
Task 2 - Count: 1
Task 1 - Count: 2
Task 2 - Count: 2
Task 1 - Count: 3
Task 1 - Count: 4
Task 2 - Count: 3
Task 1 - Count: 5
Task 2 - Count: 4
Task 2 - Count: 5

CONCLUSION
This practical demonstrates how to create threads in Java using the Runnable interface.
By implementing Runnable and passing the object to a Thread instance, the thread execution logic is
separated from the thread creation mechanism. This approach is more flexible and preferred over
extending the Thread class. The program clearly shows the parallel execution of two threads using the
Runnable interface and start() method.

You might also like