real time example of multithreading in java
real time example of multithreading in java
Here's a real-time example of multithreading in Java:
Example: A Banking System with Multiple Threads
Suppose we have a banking system that allows multiple customers to perform transactions (deposit, withdraw, check balance) simultaneously. To simulate this scenario, we can create multiple threads, each representing a customer, and use them to perform transactions concurrently.
Here's the code:
import java.awt.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BankingSystem {
private static final int NUM_THREADS = 5; // Number of customers
private static final int MAX_TRANSACTIONS = 10; // Max number of transactions per customer
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; i++) {
Customer customer = new Customer("Customer " + (i + 1));
executor.submit(new TransactionThread(customer, MAX_TRANSACTIONS));
}
// Wait for all threads to finish
executor.shutdown();
}
}
class Customer {
private String name;
private BankAccount account;
public Customer(String name) {
this.name = name;
this.account = new BankAccount(0);
}
public void performTransactions() {
// Perform multiple transactions concurrently using threads
for (int i = 0; i < BankingSystem.MAX_TRANSACTIONS; i++) {
executor.submit(new TransactionRunnable(this, account));
}
}
}
class TransactionThread implements Runnable {
private Customer customer;
private BankAccount account;
public TransactionThread(Customer customer, int numTransactions) {
this.customer = customer;
this.account = customer.getAccount();
}
@Override
public void run() {
customer.performTransactions();
}
}
class TransactionRunnable implements Runnable {
private Customer customer;
private BankAccount account;
public TransactionRunnable(Customer customer, BankAccount account) {
this.customer = customer;
this.account = account;
}
@Override
public void run() {
// Simulate transaction (e.g., deposit, withdraw, check balance)
try {
Thread.sleep((int) (Math.random() * 1000)); // Random delay to simulate processing time
double amount = Math.random() * 100; // Random transaction amount
if (customer.getAccount().getBalance() + amount <= customer.getAccount().getLimit()) {
customer.getAccount().deposit(amount);
System.out.println(customer.getName() + " deposited " + amount);
} else {
System.out.println(customer.getName() + " tried to withdraw, but account is overdrawn.");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
class BankAccount {
private double balance;
private double limit;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
this.limit = initialBalance;
}
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
public double getLimit() {
return limit;
}
}
In this example, we create a BankingSystem
class that uses an ExecutorService
to manage multiple threads (representing customers). Each customer has a Customer
object and a BankAccount
object.
The Customer
class has a method performTransactions()
that creates a new thread for each transaction. The TransactionThread
class represents a single customer performing transactions concurrently using the ExecutorService
.
The TransactionRunnable
class is responsible for simulating individual transactions (e.g., deposit, withdraw, check balance). It sleeps for a random amount of time to simulate processing time and then performs the transaction.
In the main()
method, we create multiple threads for each customer and submit them to the ExecutorService
. The system will run until all threads finish executing their transactions.
This example demonstrates how multithreading can be used to achieve concurrency in a real-world scenario, such as a banking system. By using threads to perform transactions concurrently, the system can process multiple customers' requests simultaneously, improving overall performance and responsiveness.
what is thread in java
I'd be happy to explain threads in Java!
In Java, a thread is a flow of execution within a program that can run concurrently with other threads. It's a fundamental concept in multithreading, which allows multiple tasks or processes to run simultaneously.
A thread in Java is an object of the Thread
class, and it has its own set of methods and attributes. When you create a new thread, you're essentially creating a new execution path that can run independently of other threads.
Here are some key characteristics of threads in Java:
Lightweight: Threads are much lighter than processes (which are heavy-weight). Creating and destroying a thread is much faster and more efficient than creating and destroying a process. Concurrent Execution: Threads allow for concurrent execution, meaning multiple tasks can run at the same time without blocking each other. Independent: Each thread has its own program counter, stack, and register set, making them independent and able to execute concurrently. Scheduling: The Java Virtual Machine (JVM) schedules threads based on availability of CPU resources and other factors.Now, let's talk about how you create a new thread in Java. There are several ways:
Extending the Thread Class: You can extend theThread
class and override the run()
method to define the code that should be executed by the thread.
Implementing the Runnable Interface: You can implement thepublic class MyThread extends Thread {
public void run() {
System.out.println("Hello from MyThread!");
}
}
MyThread t = new MyThread();
t.start(); // starts the thread
Runnable
interface, which has a single method called run()
that defines the code to be executed by the thread.
Using an Executor Service: Thepublic class MyRunnable implements Runnable {
public void run() {
System.out.println("Hello from MyRunnable!");
}
}
Thread t = new Thread(new MyRunnable());
t.start(); // starts the thread
ExecutorService
interface provides a way to manage threads and execute tasks concurrently.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
Runnable task = () -> System.out.println("Hello from Task " + i);
executor.submit(task); // submits the task to the thread pool
}
}
}
In this example, we create a cached thread pool using Executors.newCachedThreadPool()
and submit five tasks to execute concurrently.
These are just some of the basics of threads in Java. If you're new to multithreading, it's essential to understand the concepts of synchronization, deadlocks, and race conditions, which are crucial for building robust and efficient concurrent systems.
I hope this helps! Let me know if you have any further questions.