Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Java Multithreading Concepts

Uploaded by

deepesh
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)
9 views

Java Multithreading Concepts

Uploaded by

deepesh
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/ 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