0% found this document useful (0 votes)
5 views8 pages

Exception Multithreading

about exceptions

Uploaded by

Akhila
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)
5 views8 pages

Exception Multithreading

about exceptions

Uploaded by

Akhila
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
You are on page 1/ 8

Exception Handling Questions

1. What is Exception Handling in Java?

◦ Exception handling is a mechanism that handles runtime errors, preventing the


program from crashing unexpectedly.
2. What are the types of exceptions in Java?

◦ Checked Exceptions: Checked at compile-time (e.g., IOException,


SQLException).
◦ Unchecked Exceptions: Occur at runtime (e.g., NullPointerException,
ArrayIndexOutOfBoundsException).
3. What is the difference between throw and throws in Java?

◦ throw: Used to explicitly throw an exception.


◦ throws: Declares exceptions that a method might throw.

4. What is the difference between final, finally, and finalize?

◦ final: Used for constants, methods (cannot be overridden), and classes (cannot be
inherited).
◦ finally: A block that always executes, regardless of whether an exception
occurs.
◦ finalize: A method used for garbage collection before an object is destroyed.
5. What are the key components of exception handling?

◦ try: Contains the code that may throw an exception.


◦ catch: Catches and handles exceptions.
◦ finally: Executes code regardless of exception occurrence.
◦ throw: Throws an exception explicitly.
◦ throws: Declares exceptions that a method can throw.
6. Can a try block exist without a catch block?

◦ Yes, but it must have a finally block.


7. What is the hierarchy of Java exceptions?

Throwable

8. ├── Error
9. └── Exception
10. ├── RuntimeException
11. ├── IOException
12. ├── SQLException
13.

14. What happens when an exception is not handled?


◦ The program terminates abruptly and prints the exception stack trace.
15. Can we have multiple catch blocks?

◦ Yes, but they should be ordered from speci c to general exception types.
16. What is a custom exception in Java?

• A user-de ned exception created by extending the Exception clas

Q1: What is multi-threading in Java?

• Multi-threading allows multiple tasks (threads) to run concurrently to improve


performance.
• Java supports multi-threading via the Thread class and Runnable interface.
Example:

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running...");
}
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Start the thread
}
}

Q2: What is the difference between a Process and a Thread?

Feature Process Thread


De nition A program in execution A lightweight unit inside a process
Memory Separate memory space Shares memory within a process
Communicatio Uses IPC (Inter-Process
Communicates easily within the process
n Communication)
Creation Slower Faster
Running multiple tasks inside a
Example Running multiple programs
program

Q3: How to create a thread in Java?

✅ There are two ways to create a thread:


fi
fi
fi
1. Extending Thread class
2. Implementing Runnable interface
Example using Thread class:

class MyThread extends Thread {


public void run() {
System.out.println("Thread running using Thread
class.");
}
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
Example using Runnable interface:

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread running using Runnable
interface.");
}
}

public class Main {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
✅ Using Runnable is preferred as it allows multiple classes to extend other classes.

2. Thread Lifecycle
Q4: What are the states of a thread in Java?

A thread has ve states:

1. NEW → Created but not started.


2. RUNNABLE → Ready to run.
3. BLOCKED → Waiting for a resource.
fi
4. WAITING/TIMED_WAITING → Waiting inde nitely or for a certain time.
5. TERMINATED → Finished execution.
Example:

Thread t = new Thread();


System.out.println(t.getState()); // Output: NEW

3. Thread Methods
Q5: What is the difference between start() and run() method in Java
threads?

Method Description
start( Creates a new thread and calls run() method in a separate
) thread.
run() Runs in the main thread, does not start a new thread.

Example:

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running...");
}
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.run(); // Runs in main thread
t1.start(); // Runs in new thread
}
}

Q6: What is the use of sleep() method in Java?

• Pauses execution of the thread for a speci c time.


• Used to simulate delays.
Example:

class MyThread extends Thread {


public void run() {
try {
for (int i = 1; i <= 5; i++) {
fi
fi
System.out.println(i);
Thread.sleep(1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}

Q7: What is thread priority in Java?

• Each thread has a priority (1 to 10).


• Higher priority threads run before lower priority ones.
Example:

Thread t1 = new Thread();


t1.setPriority(Thread.MAX_PRIORITY); // Highest priority (10)
Priority Constant Value
Thread.MIN_PRIORITY 1
Thread.NORM_PRIORIT 5
Y (default)
Thread.MAX_PRIORITY 10

4. Thread Synchronization
Q8: What is thread synchronization?

• Synchronization prevents multiple threads from accessing a shared resource at the


same time.
• Achieved using the synchronized keyword.
Example:

class Counter {
private int count = 0;

synchronized void increment() { // Lock on this method


count++;
}

int getCount() {
return count;
}
}

public class Main {


public static void main(String[] args) {
Counter counter = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++)
counter.increment();
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++)
counter.increment();
});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println(e);
}

System.out.println("Final count: " +


counter.getCount()); // Output: 2000
}
}

Q9: What is deadlock in multi-threading?

• Deadlock occurs when two or more threads wait inde nitely for resources held by each
other.
Example:

class DeadlockExample {
static final Object resource1 = new Object();
fi
static final Object resource2 = new Object();

public static void main(String[] args) {


Thread t1 = new Thread(() -> {
synchronized (resource1) {
System.out.println("Thread 1: Locked
resource1");
synchronized (resource2) {
System.out.println("Thread 1: Locked
resource2");
}
}
});

Thread t2 = new Thread(() -> {


synchronized (resource2) {
System.out.println("Thread 2: Locked
resource2");
synchronized (resource1) {
System.out.println("Thread 2: Locked
resource1");
}
}
});

t1.start();
t2.start();
}
}
Solution: Avoid nested locks or use ReentrantLock.

5. Advanced Multi-threading
Q10: What is ExecutorService in Java?

• ExecutorService is a thread pool manager that manages multiple threads ef ciently.


Example:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {


public static void main(String[] args) {
fi
ExecutorService executor =
Executors.newFixedThreadPool(3);

for (int i = 1; i <= 5; i++) {


final int taskNumber = i;
executor.submit(() -> {
System.out.println("Executing task " +
taskNumber);
});
}

executor.shutdown();
}
}
✅ Advantages:

• Better thread management.


• Prevents unnecessary thread creation.

You might also like