Java Interview Questions
Java
Web DevelopmentBackendQuestion 20
How do you create a thread in Java?
Answer:
In Java, you can create and manage threads in several ways. The two most common methods are:
- Extending the
Thread
class. - Implementing the
Runnable
interface.
1. Extending the Thread
Class
To create a thread by extending the Thread
class, you need to create a new class that extends Thread
and override the run
method. The run
method contains the code that constitutes the new thread's task.
Example:
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // Start the first thread
t2.start(); // Start the second thread
}
}
2. Implementing the Runnable
Interface
To create a thread by implementing the Runnable
interface, you need to create a class that implements Runnable
and override the run
method. You then create a Thread
object, passing the Runnable
object to the Thread
constructor, and start the thread using the start
method.
Example:
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
t1.start(); // Start the first thread
t2.start(); // Start the second thread
}
}
Choosing Between Thread
and Runnable
- Runnable Interface: Preferred in most cases because it separates the task from the thread. This promotes better object-oriented design and allows you to implement other interfaces or extend other classes.
- Thread Class: Can be used for simplicity or when you need to override additional
Thread
methods.
Example with Lambda Expression
In Java 8 and later, you can use lambda expressions to create a thread, which makes the code more concise.
Example:
public class LambdaThreadExample {
public static void main(String[] args) {
Runnable task = () -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start(); // Start the first thread
t2.start(); // Start the second thread
}
}
Key Points
- start() Method: To begin execution of the thread, you must call the
start
method, which in turn calls therun
method. - sleep() Method: The
sleep
method pauses the thread for a specified time, allowing other threads to execute. - Thread Lifecycle: A thread can be in one of several states:
NEW
,RUNNABLE
,BLOCKED
,WAITING
,TIMED_WAITING
, orTERMINATED
.
Conclusion
Creating threads in Java can be done either by extending the Thread
class or by implementing the Runnable
interface. Using Runnable
is generally preferred for its flexibility and adherence to object-oriented principles. With Java 8 and later, lambda expressions can be used to make the code more concise and readable. Understanding how to create and manage threads is essential for developing concurrent and parallel applications in Java.