Java Multithreading Interview Questions and Answers
Ques 1. What is multithreading?
Multithreading is the concurrent execution of two or more threads to achieve parallelism in a program.
Example:
In Java, you can create a multithreaded program by extending the Thread class or implementing the Runnable interface.
Ques 2. How do you create a thread in Java?
You can create a thread by extending the Thread class or implementing the Runnable interface.
Example:
Example using Thread class:
class MyThread extends Thread {
public void run() {
/* Thread logic */
}
}
Ques 3. Explain the difference between Thread and Runnable.
Thread is a class in Java that provides methods to create and perform operations on a thread. Runnable is an interface that must be implemented by a class to be executed by a thread.
Example:
class MyRunnable implements Runnable {
public void run()
{ /* Runnable logic */
}
}
Ques 4. What is the purpose of the sleep() method in Java?
The sleep() method is used to pause the execution of the current thread for a specified amount of time.
Example:
try { Thread.sleep(1000); }
catch (InterruptedException e) { e.printStackTrace(); }
Ques 5. How can you achieve synchronization in Java?
You can achieve synchronization in Java using the synchronized keyword or using locks.
Example:
Example using synchronized keyword:
synchronized void myMethod() { /* Synchronized code */ }
Most helpful rated by users: