Interview Questions: Multithreading-Part-1
15 min readAug 13, 2023
Q1: What is a thread in Java?
Answer: A thread in Java is the smallest unit of execution within a process. It is a lightweight sub-process that shares the same memory space as other threads in the same process. Threads allow multiple tasks to be executed concurrently, enhancing the application’s efficiency.
Q2: How can you create a thread in Java?
Answer: There are two ways to create a thread in Java:
- By extending the Thread class.
- By implementing the Runnable interface.
Creating thread by extending Thread class:
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Hello this is inside MyThread's run method");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new MyThread();
thread.start();
}
}
Creating thread by implementing Runnable interface:
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Hello this is inside MyRunnable's run method");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable…