Java 10
Java 10
PRACTICAL NO 10
Name of practical: Write a program in Java to implement multithreading.
In Java, both the Runnable interface and the Thread class are used to create and manage
threads. The Runnable interface is a functional interface that is implemented by a class whose
instances are intended to be executed by a thread. It contains a single abstract method called
run() which needs to be overridden.
The Thread class itself represents a thread of execution. It provides constructors and methods to
create and manage threads, including the ability to start a thread, stop it, and perform operations
on it. It also implements the Runnable interface.
The Runnable interface is preferred over extending the Thread class for these reasons:
1. Separation of concerns: It separates the task (what to execute) from the thread (how to
execute it), promoting cleaner design.
2. Single inheritance: Java allows a class to extend only one class. By using Runnable,
you can extend another class if needed.
3. Better reusability: You can reuse the same Runnable task across multiple threads,
whereas a Thread instance is tied to a single task.
4. Thread pools: Runnable is better suited for use with thread pools, which efficiently
manage multiple threads.
5. Encourages composition: Runnable favors composition over inheritance, which is a
good object-oriented design principle. Program
class BankAccount {
private int balance = 2000; // Initial balance
Practical no: 10
Aqsa 22DCS008
balance -= amount;
System.out.println(Thread.currentThread().getName() + " successfully withdrew. New
Balance: " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " attempted to withdraw: " +
amount + " but insufficient funds!");
}
}
Practical no: 10
Aqsa 22DCS008
customer2.start();
customer2.join(); // Wait for customer2 to finish
customer3.start();
customer3.join(); // Wait for customer3 to finish
customer4.start();
customer4.join(); // Wait for customer4 to finish
Output
Practical no: 10