Java Multithreading Concepts

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Java Multithreading Concepts

1. Differentiate between Multiprocessing and Multithreading:

Multiprocessing:

- Involves multiple processors executing different tasks simultaneously.

- Each process has its own memory space.

- Suitable for CPU-bound tasks.

Multithreading:

- Involves multiple threads running within a single process.

- Threads share the same memory space.

- Suitable for I/O-bound or lightweight tasks.

2. Two ways of creating threads and their differences:

1. Extending the Thread class:

- A class can extend the java.lang.Thread class and override the run() method.

- Example:

class MyThread extends Thread {

public void run() {

System.out.println("Thread running");

MyThread t = new MyThread();

t.start();

2. Implementing the Runnable interface:

- A class can implement the java.lang.Runnable interface and pass it to a Thread object.
- Example:

class MyRunnable implements Runnable {

public void run() {

System.out.println("Thread running");

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

t.start();

Difference:

- Extending Thread prevents inheriting from other classes, while implementing Runnable allows

multiple inheritance.

- Implementing Runnable is more flexible and recommended.

3. Explain Thread lifecycle:

The lifecycle of a thread includes the following states:

- New: The thread is created but not yet started.

- Runnable: The thread is ready to run but waiting for CPU time.

- Running: The thread is actively executing.

- Blocked/Waiting: The thread is waiting for a resource or signal.

- Terminated: The thread has completed execution.

4. Explain the concept of daemon thread:

Daemon threads are background threads that provide services to user threads. They are terminated

by the JVM when all user threads finish execution.

- Example: Garbage collection thread.

- To make a thread a daemon thread, use the setDaemon(true) method before starting the thread.

- Daemon threads should not be used for critical tasks as they do not prevent the JVM from shutting
down.

You might also like