0% found this document useful (0 votes)
5 views

Advance_Java_answers

The document provides an overview of the Java Collection Framework, detailing its components, key interfaces like Map and List, and classes such as LinkedList and TreeSet. It also covers multithreading concepts, including thread lifecycle, advantages of multithreading, and the use of CallableStatement in JDBC. Additionally, it highlights the benefits of using PreparedStatement over Statement for executing SQL queries.

Uploaded by

jesaboc231
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Advance_Java_answers

The document provides an overview of the Java Collection Framework, detailing its components, key interfaces like Map and List, and classes such as LinkedList and TreeSet. It also covers multithreading concepts, including thread lifecycle, advantages of multithreading, and the use of CallableStatement in JDBC. Additionally, it highlights the benefits of using PreparedStatement over Statement for executing SQL queries.

Uploaded by

jesaboc231
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1.What is Collection Framework?

Ans : The Collection Framework in Java is a set of classes and interfaces that
provide a unified architecture to store, retrieve, and manipulate a group of
objects efficiently. It is part of the java.util package and provides ready-to-
use data structures like List, Set, Queue, and Map.

Key Features of Collection Framework


Reusable Data Structures – Predefined classes like ArrayList, HashSet, etc.
Consistent API – Follows a common set of methods across all collections.
Reduces Development Time – No need to write custom data structures.
Efficient Algorithms – Built-in sorting, searching, and manipulation functions.
Generics Support – Type safety ensures compile-time checking.
--------------------------------------------------

2. What is the use of Map interface?


Ans : The Map interface in Java (part of java.util) is used to store key-value
pairs, where each key is unique, and values can be duplicated. It does not
extend Collection but is a key part of the Java Collection Framework.

Key Features:
Key-Value Mapping: Each key is mapped to a specific value.
Unique Keys: No duplicate keys allowed.
Efficient Lookups: Provides fast retrieval of values based on keys.
--------------------------------------------------

3. What is the use of LinkedList class?


Ans The LinkedList class in Java (part of java.util) is a doubly linked list
implementation of the List and Deque interfaces. It allows fast insertions and
deletions but is slower than ArrayList for random access.

✅ Doubly Linked Structure – Each node has references to the previous and next


nodes.
Fast Insertions/Deletions – O(1) complexity for adding/removing elements from

✅✅
the beginning or middle.
Implements List and Deque – Supports queue and stack operations.
Allows Duplicates & Nulls – Just like ArrayList.
--------------------------------------------------

4. What is Enumeration interface? (Question 7 duplicate)


Ans The Enumeration interface (in java.util) is used to traverse elements of
legacy collections (like Vector and Hashtable). It was introduced in Java 1.0
but is now mostly replaced by Iterator.

✅✅
Key Features:
Read-Only Access – Cannot modify elements during traversal.

✅ Works with Legacy Classes – Used with Vector, Stack, Hashtable.


Sequential Element Access – One-by-one traversal.
--------------------------------------------------

5.List components for collection framework.


Ans : The Java Collection Framework consists of several key components,
including interfaces, implementations (classes), and utility classes, which
provide efficient ways to store and manipulate data.

- Core Interfaces: These define the fundamental structure of collections:


- Collection (Root interface for all collections)
- List (Ordered, allows duplicates) → ArrayList, LinkedList, Vector
- Set (Unordered, unique elements) → HashSet, TreeSet, LinkedHashSet
- Queue (FIFO, used for processing elements) → PriorityQueue, Deque
- Map (Key-value pairs, unique keys) → HashMap, TreeMap, Hashtable

- Implementations (Classes): These provide concrete implementations of the


interfaces:
- List Implementations: ArrayList, LinkedList, Vector
- Set Implementations: HashSet, LinkedHashSet, TreeSet
- Queue Implementations: PriorityQueue, ArrayDeque
- Map Implementations: HashMap, TreeMap, LinkedHashMap, Hashtable

- Utility Classes: These offer additional functionalities for working with


collections:
- Collections (Provides sorting, searching, and synchronization utilities)
- Arrays (Offers utility functions for array manipulation)

This structured framework ensures efficient data management by providing


reusable, optimized, and well-organized collection types.
--------------------------------------------------

6. What is TreeSet?
Ans : TreeSet is a class in Java’s Collection Framework that implements the Set
interface using a Red-Black Tree. It stores unique elements in sorted order and
does not allow duplicates.

Features of TreeSet:
Sorted Order: Automatically sorts elements in ascending order (natural
ordering).
No Duplicates: Ensures that no duplicate elements are stored.
Implements NavigableSet: Supports navigation methods like higher(), lower(),
ceiling(), floor().
Performance: Operations like add, remove, and search have O(log n) time
complexity due to the Red-Black Tree structure.
--------------------------------------------------

8. Define thread priority. (Question 13 is Duplicate)


Ans : Thread priority in Java is a mechanism to determine the relative
importance of different threads in a multithreaded environment. Each thread has
a priority level that helps the operating system decide when the thread should
be executed relative to other threads.

Key Points:
Priority Range: The thread priority is represented by an integer value between
Thread.MIN_PRIORITY (1) and Thread.MAX_PRIORITY (10), with a default value of
Thread.NORM_PRIORITY (5).
Thread Scheduling: Threads with higher priority are generally executed before
threads with lower priority, but the actual scheduling depends on the underlying
operating system's thread scheduler.
Non-Preemptive Nature: Java's thread priority does not guarantee exact behavior,
as thread scheduling is ultimately controlled by the operating system.

--------------------------------------------------

9. What is the use of notifyAll () method?


Ans : The notifyAll() method is used in Java to wake up all the threads that are
currently waiting on the object's monitor (lock). It is a method of the Object
class and is used in synchronization contexts to manage thread communication.

Key Points:
Used with Synchronized Blocks: notifyAll() can only be called from within a
synchronized block or method.
Wakes All Waiting Threads: It notifies all threads that are waiting on the same
object's monitor to wake up and compete for the lock again.
Thread Communication: It is typically used in scenarios where multiple threads
are waiting for a condition to change, and once that condition is met, all
waiting threads should proceed.
--------------------------------------------------

10. Which states occurs in life cycle of multithreading.


Ans : The life cycle of a thread in Java involves several states, controlled by
the Thread Scheduler. A thread can transition between these states based on its
execution, events, and synchronization.

1. New (Born) State


A thread is in the new state when it is created but has not yet started
executing.
The thread is not yet eligible for CPU time.
This state is entered when a thread instance is created using the Thread class
but before calling start().

2. Runnable State
The thread enters the runnable state after calling start(), but it is not
necessarily running.
In this state, the thread is eligible to run, but it may not be running
immediately due to CPU scheduling.
It may be running or waiting for the CPU to execute its code.
Threads can enter this state by calling start() or if they return to this state
after sleeping or waiting.

3. Blocked (Waiting) State


A thread enters the blocked state when it wants to access a synchronized
resource that is already locked by another thread.
The thread is temporarily prevented from executing.
This state occurs when a thread attempts to acquire a lock and the lock is
already held by another thread.

4. Waiting State
A thread enters the waiting state when it is waiting for another thread to
perform a particular action.
A thread can be placed in this state by calling methods like wait(), join(), or
sleep() (for a specific time).
The thread will remain in the waiting state until it is notified, the specified
time has elapsed, or the action it is waiting for occurs.

5. Timed Waiting State


A thread enters the timed waiting state when it is in a waiting state but only
for a specified amount of time.
This state can occur when calling methods like:
sleep(millis) (where the thread sleeps for a specific time).
join(millis) (where the thread waits for a specified time for another thread to
complete).
wait(millis) (where it waits for a specific time before resuming).

6. Terminated (Dead) State


A thread enters the terminated state when it has completed its execution or has
been aborted.
In this state, the thread has finished its task, and its resources are released.

Thread Lifecycle Flow:


New → 2. Runnable → 3. Running (based on scheduling)
→ 4. Blocked/Waiting → 5. Timed Waiting
→ 6. Terminated
--------------------------------------------------

11. Which packages are required of Java database connectivity?


Ans : Java Database Connectivity (JDBC) is a standard Java API used for
connecting to and interacting with relational databases. To use JDBC in a Java
application, the following packages are required:

1)java.sql

The core package for JDBC, containing classes and interfaces for database
connections, SQL execution, and result processing.
Key classes and interfaces:
Connection – Establishes a connection to the database.
Statement – Executes SQL queries.
PreparedStatement – Precompiled SQL queries for efficiency.
ResultSet – Represents the result of a query.
SQLException – Handles database-related exceptions.
DriverManager – Manages database drivers.
DataSource – Provides an alternative to DriverManager for establishing a
connection.

2)javax.sql

Contains advanced features for JDBC, typically used for connection pooling and
data source management.
Key classes and interfaces:

DataSource – Used for pooling and managing connections, providing a more


efficient way to establish a database connection than DriverManager.
ConnectionPoolDataSource – Interface for pooling connections.
PooledConnection – Used to manage pooled connections.
SQLInput and SQLOutput – Used for reading and writing complex types in JDBC.
--------------------------------------------------

12. What is Transaction in database?


Ans : A transaction in a database is a sequence of one or more SQL operations
executed as a single unit of work. A transaction is used to ensure data
integrity and consistency, even in the presence of system failures or errors.

Key Properties of Transactions (ACID):


Transactions in databases adhere to the ACID properties, which stand for:

Atomicity:
The entire transaction is treated as a single atomic unit. This means that
either all operations within the transaction are executed successfully, or none
are. If any part of the transaction fails, the entire transaction is rolled
back.

Consistency:
A transaction takes the database from one consistent state to another. After the
transaction is completed, the database must be in a valid state according to its
rules, constraints, and integrity checks.

Isolation:
Transactions are isolated from each other. This means that the operations of one
transaction are not visible to other transactions until the transaction is
committed. This prevents data inconsistencies in concurrent environments.

Durability:
Once a transaction is committed, the changes made to the database are permanent.
Even in the case of system crashes, the changes will not be lost.

Types of Transactions: Simple Transaction and Distributed Transaction


--------------------------------------------------

14. What is the use of callable statement?


Ans : A CallableStatement is an interface in JDBC used to execute SQL stored
procedures. It is a specialized version of the Statement interface that allows
you to call database stored procedures or functions directly from your Java
application.

Key Features of CallableStatement:


Execute Stored Procedures: It is used to call stored procedures and functions in
the database that may involve multiple SQL statements.
Input and Output Parameters: You can pass input and output parameters to and
from the stored procedure. This makes it ideal for handling complex database
operations.
Callable SQL Functions: It supports output parameters (for retrieving results
from stored procedures) and return values.
--------------------------------------------------

15. Define metadata.


Ans : Metadata in the context of databases refers to data about data. It
provides descriptive information about the structure, organization, and
properties of the data stored within a database. Essentially, it helps to define
how the data is organized, how it can be accessed, and what kind of data it
contains.

In JDBC, metadata refers to information about the database itself (e.g., tables,
columns, supported SQL features). The DatabaseMetaData and ResultSetMetaData
classes are commonly used to retrieve this metadata.

1. DatabaseMetaData:
Used to retrieve information about the database's structure, such as its tables,
columns, supported features, etc.
Example methods:
getTables(): Returns information about tables in the database.
getColumns(): Provides information about columns in a specified table.
getDatabaseProductName(): Retrieves the name of the database product.

2. ResultSetMetaData:
Provides metadata about the result set returned by a query (e.g., number of
columns, column names, data types).
Example methods:
getColumnCount(): Gets the number of columns in the result set.
getColumnName(int columnIndex): Gets the name of a column.
getColumnType(int columnIndex): Gets the data type of a column.
--------------------------------------------------

16. State the use of Iterator and List Iterator.


Ans : Both Iterator and ListIterator are interfaces in Java that allow you to
iterate over a collection, such as a List, Set, or other collection types. They
are part of the Java Collections Framework and provide a way to traverse through
the elements in a collection, but they have different features and uses.

Iterator:
The Iterator interface provides methods to iterate over elements in a collection
(typically List, Set, etc.). It allows you to traverse the collection in a
forward direction and perform actions like removing elements during iteration.

Key Methods of Iterator:


hasNext():
Returns true if there are more elements to iterate over.
Example: while (iterator.hasNext())
next():
Returns the next element in the iteration.
Example: Object obj = iterator.next()
remove():
Removes the current element from the collection (optional operation).
Example: iterator.remove();

ListIterator:
The ListIterator is an extension of the Iterator interface, specifically
designed for List collections (such as ArrayList, LinkedList, etc.). It allows
both forward and backward iteration, and also provides more powerful features,
like modifying elements and adding new elements during iteration.

Key Methods of ListIterator:


hasNext():
Returns true if there is another element in the list (same as in Iterator).
next():
Returns the next element in the list (same as in Iterator).

hasPrevious():
Returns true if there is an element before the current position (unique to
ListIterator).

previous():
Returns the previous element in the list (unique to ListIterator).

add(E e):
Adds an element to the list at the current position (unique to ListIterator).

set(E e):
Replaces the last element returned by next() or previous() with the specified
element (unique to ListIterator).
-------
Key Differences:

Direction of Iteration:
Iterator: Can only iterate forward.
ListIterator: Can iterate both forward and backward.

Modification:
Iterator: Can remove elements during iteration but cannot modify or add
elements.
ListIterator: Can add, modify, and remove elements during iteration.

--------------------------------------------------

17. What is Multithreading? Write its advantages?


Ans : Multithreading is a concurrent execution technique where multiple threads
run independently but share the same resources, such as memory, within a
program. Each thread represents a separate path of execution, allowing different
parts of a program to run simultaneously.

In Java, multithreading is a fundamental part of concurrent programming, and the


Java Virtual Machine (JVM) handles threads efficiently for tasks like file
processing, network communication, or complex computations.

How Multithreading Works:


A thread is the smallest unit of execution within a program.
Multiple threads can be executed in parallel or concurrently, depending on the
system's core capabilities (single-core vs. multi-core processors).
Each thread has its own execution context, but they share the same memory space,
making thread management an essential aspect of multithreading.

Advantages of Multithreading:
Improved Performance and Responsiveness:
Multithreading allows parts of a program to run concurrently, improving overall
performance by utilizing the CPU more efficiently.
In user interface (UI) applications, multithreading ensures that the UI remains
responsive while other tasks (like background data processing) are running.

Better CPU Utilization:


On multi-core processors, multiple threads can run on different cores, utilizing
the full potential of the hardware. This can result in better performance,
especially for CPU-intensive tasks.

Faster Task Execution:


By breaking a task into smaller subtasks that can be run simultaneously,
multithreading speeds up the completion of tasks. For example, file downloads or
database queries can be executed in parallel.
Resource Sharing:
Threads within the same process share memory space, allowing for more efficient
communication and data sharing, compared to processes, which have separate
memory areas.

Cost-Efficiency:
Creating and managing threads is less resource-intensive than creating separate
processes. Threads are lightweight, meaning they require less memory and
resources.

Asynchronous Execution:
Multithreading allows for asynchronous execution, where tasks can be carried out
in the background without blocking the main thread. For example, network
requests or file operations can be handled without freezing the main program.

Scalability:
As the number of cores in processors increases, the performance benefits of
multithreading scale significantly. This enables applications to handle more
tasks concurrently and efficiently.
--------------------------------------------------

18. What is the advantage of using prepared statement over statement?


Ans : In Java, PreparedStatement and Statement are both used to execute SQL
queries, but PreparedStatement offers several advantages over Statement when it
comes to security, performance, and maintainability.

Key Differences:
Statement:
Executes simple SQL queries or commands directly. SQL queries are compiled and
executed every time they are run, which can be inefficient and prone to errors
in case of repeated execution of the same query.

PreparedStatement:
A precompiled SQL query that allows for parameterized queries, making it more
efficient and secure. The SQL query is compiled only once and can be executed
multiple times with different parameter values.

Advantages of Using PreparedStatement Over Statement:


1. Improved Performance (Pre-compilation of SQL):
2. Security (Prevention of SQL Injection):
3. Code Readability and Maintainability:
4. Automatic Handling of Input Data Types:
5. Reduced Risk of Errors:
6. Better Resource Management:
7. Support for Multiple Parameter Types:
--------------------------------------------------

19. What is ResultSet?


Ans : A ResultSet in Java is an interface that represents the result of a SQL
query. It is used to retrieve and manipulate the data returned from a database
when a query is executed using a Statement or PreparedStatement.

A ResultSet object acts as a cursor that points to the current row of data in
the result set. You can use it to iterate over the rows and retrieve column
values of each row.

Key Features of ResultSet:

Iterating Through Data:


You can move through the rows in a result set using methods like next() and
previous().
ResultSet acts like a cursor that starts at the beginning (before the first row)
and can be moved forward through the data.
Accessing Data:
You can access the data of each column using methods like getString(), getInt(),
getDate(), etc. based on the column's data type.

Dynamic Navigation:
You can use methods to move to a specific row (e.g., absolute(), first(),
last()) or to navigate one row at a time (e.g., next(), previous()).

Scrollable and Updatable ResultSet:


A scrollable result set allows you to move both forward and backward, whereas a
regular result set (the default) only allows forward navigation.
A updatable result set allows modifications to the data (insert, update, delete)
directly in the database.

--------------------------------------------------

20. What is JDBC driver? List its types. (Question 22 is Duplicate)


Ans : A JDBC Driver is a software component that enables Java applications to
interact with a database using the Java Database Connectivity (JDBC) API. It
acts as a bridge between Java applications and databases, translating Java calls
into database-specific calls and vice versa.

In simple terms, JDBC drivers allow Java applications to send SQL commands to a
database and retrieve the results.

Types of JDBC Drivers


There are four types of JDBC drivers based on their architecture and how they
interact with the database:
1. Type-1 Driver (JDBC-ODBC Bridge Driver)
2. Type-2 Driver (Native-API Driver)
3. Type-3 Driver (Network Protocol Driver)
4. Type-4 Driver (Thin Driver)

Conclusion
Type-4 drivers are the most commonly used due to their high performance,
platform independence, and ease of deployment.
Type-3 drivers are useful when you need to connect to multiple databases without
worrying about database-specific drivers.
Type-2 and Type-1 drivers are less common today, but they are still used in
certain legacy systems or specific configurations.

--------------------------------------------------
21. List any two methods for creating transaction.
Ans : Two Methods for Creating Transactions in JDBC
In JDBC, a transaction is a sequence of SQL operations executed as a single unit
of work. Transactions ensure data integrity and consistency by allowing
operations like commit and rollback to control the transaction flow. There are
two main ways to manage transactions in JDBC:

1. Using setAutoCommit(false) Method


By default, JDBC operates in auto-commit mode, meaning each individual SQL
statement is treated as a separate transaction and is committed immediately
after execution. To control transactions manually, you can disable auto-commit
using the setAutoCommit(false) method. This allows you to group multiple
statements into a single transaction.

2. Using Connection.setSavepoint() Method


In addition to manually controlling the commit and rollback, you can set
savepoints in a transaction using the setSavepoint() method. A savepoint allows
you to create intermediate checkpoints within a transaction. If something goes
wrong, you can roll back to a specific savepoint rather than rolling back the
entire transaction.
Summary:
Using setAutoCommit(false): Disables auto-commit mode to control the entire
transaction and commit/rollback based on your logic.
Using setSavepoint(): Allows you to set intermediate points (savepoints) in the
transaction for partial rollbacks.
These two methods are the primary ways to manage transactions in JDBC, giving
you fine control over database operations and ensuring data consistency.

--------------------------------------------------
23. What is savepoint? What is its use?
Ans : A Savepoint is a mechanism in JDBC that allows you to set intermediate
points within a transaction. It enables you to mark a specific point in a
transaction so that you can roll back to that point if something goes wrong,
without affecting the entire transaction. This allows for more granular control
over the transaction process.

Key Points about Savepoints:


Set Savepoint: A savepoint is created by calling the setSavepoint() method on a
Connection object. This marks a specific point within a transaction.
Rollback to Savepoint: If an error occurs after the savepoint, you can roll back
to that specific savepoint (rather than rolling back the entire transaction)
using rollback(Savepoint savepoint).
Transaction Control: You can still commit or roll back the entire transaction
after rolling back to a savepoint, depending on the outcome of the transaction.

Use of Savepoint:
Partial Rollback: When working with complex transactions that involve multiple
operations, a savepoint allows you to rollback to an intermediate point in the
transaction, rather than rolling back the entire set of operations. This helps
prevent losing all changes when only part of the transaction fails.

Error Handling: If an error occurs during a transaction, you can use a savepoint
to backtrack to a point where the transaction was still in a valid state. You
can then correct the error and proceed with the rest of the transaction.

Flexible Transaction Management: Savepoints give you flexibility in handling


multiple SQL statements within a transaction. If only a few operations fail, you
can undo just those parts without affecting others.
--------------------------------------------------

24. What is the use role of Connection interface.


Ans : Role of Connection Interface in JDBC
The Connection interface in JDBC (Java Database Connectivity) plays a
fundamental role in managing database connections. It acts as a bridge between
Java applications and the database, providing methods to establish, manage, and
terminate connections.

Key Roles and Uses of the Connection Interface:


1. Establishing a Connection:
2. Managing Transactions:
3. Creating Statements:
4. Managing Database Metadata
5. Handling Connection Pooling
6. Closing the Connection
7. Managing Isolation Levels

--------------------------------------------------
25. Compare thread and process. Any two points.
Ans : Comparison between Thread and Process

1. Definition and Basic Unit:


- Thread: A thread is the smallest unit of execution within a process.
Multiple threads can exist within a process and share resources such as memory
space.
- Process: A process is an independent program in execution. It has its own
memory space and system resources. Each process operates in its own address
space and does not share memory with other processes unless explicitly
communicated.

Key Point: Threads share the same memory space within a process, while
processes have their own independent memory.

2. Creation and Overhead:


- Thread: Threads are lightweight and have lower overhead because they share
the same resources of the parent process, such as memory and file handles.
- Process: Processes are heavyweight and have higher overhead as they require
their own memory allocation, system resources, and management by the operating
system.

Key Point: Creating threads is faster and consumes fewer resources than
creating new processes.

--------------------------------------------------
26. Give the purpose of synchronization. (Question 27 is duplicate)
Ans : Synchronization is used in Java to control access to shared resources by
multiple threads. Its primary purpose is to ensure that only one thread can
access a particular section of code (or resource) at a time, preventing data
inconsistency and race conditions in concurrent environments.

Key Purposes of Synchronization:

1. Preventing Data Inconsistency:


- In a multithreaded environment, when multiple threads access and modify
shared data (such as a variable or a collection), there is a risk of data
corruption or inconsistency. Synchronization ensures that only one thread can
access and modify the shared resource at any given time.
- Without synchronization, multiple threads could update the same data
simultaneously, causing unpredictable results.

2. Avoiding Race Conditions:


- A race condition occurs when two or more threads try to modify shared data
concurrently, leading to unpredictable behavior. Synchronization ensures that
only one thread can execute critical sections of code that modify shared data,
thus avoiding race conditions.

Example: If two threads try to increment the same counter at the same time,
the final value might not be correct unless synchronization is used.

3. Ensuring Thread Safety:


- Synchronization helps to ensure that a method or block of code is executed
by only one thread at a time, making it **thread-safe**. This is crucial when
threads interact with shared resources, such as files, databases, or user
interfaces, to maintain consistency and avoid errors.

--------------------------------------------------

28. Differentiate between Comparator Interface and Enumeration Interface.


Ans : Difference between Comparator Interface and Enumeration Interface
While both Comparator and Enumeration are part of Java's collections framework,
they serve different purposes and are used in different contexts. Below is a
comparison highlighting their key differences:

Summary of Differences:
- Comparator is used for sorting and defining the order of elements in a
collection, whereas Enumeration is used for iterating over elements in legacy
collections.
- Comparator allows custom ordering of objects but does not modify the elements,
while Enumeration allows iteration but does not support modifying the
collection.
- Comparator is still widely used for sorting, while Enumeration is considered
outdated, replaced by Iterator.

--------------------------------------------------

29. Write a program to display “BYE CORONA…” message n times using Runnable
interface.

import java.util.Scanner;

// Implementing Runnable interface


class ByeCorona implements Runnable {
private int n;

public ByeCorona(int n) {
this.n = n;
}

@Override
public void run() {
for (int i = 1; i <= n; i++) {
System.out.println(i + ". BYE CORONA...");
try {
Thread.sleep(500); // Adding a slight delay for better
visualization
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
}
}

public class ByeCoronaMain {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of times to display the message: ");
int n = scanner.nextInt();
scanner.close();

// Creating a Runnable instance


ByeCorona task = new ByeCorona(n);

// Creating a Thread with Runnable instance


Thread thread = new Thread(task);

// Starting the thread


thread.start();
}
}
--------------------------------------------------

30. Write a program for multiple treads.

class MyTask implements Runnable {


private String message;

public MyTask(String message) {


this.message = message;
}

@Override
public void run() {
for (int i = 1; i <= 5; i++) { // Each thread prints 5 times
System.out.println(Thread.currentThread().getName() + ": " + message
+ " (" + i + ")");
try {
Thread.sleep(500); // Simulate processing time
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "
interrupted.");
}
}
}
}

public class MultiThreadDemo {


public static void main(String[] args) {
// Creating multiple Runnable tasks
MyTask task1 = new MyTask("Thread 1 Running");
MyTask task2 = new MyTask("Thread 2 Running");
MyTask task3 = new MyTask("Thread 3 Running");

// Creating threads
Thread thread1 = new Thread(task1, "Thread-A");
Thread thread2 = new Thread(task2, "Thread-B");
Thread thread3 = new Thread(task3, "Thread-C");

// Starting threads
thread1.start();
thread2.start();
thread3.start();
}
}

--------------------------------------------------

You might also like