How does Java handle multithreading? Explain the differences between the Thread class and the Runnable interface.
Java handles multithreading using the Thread
class and the Runnable
interface. You can create a new thread by extending the Thread
class or implementing the Runnable
interface. Extending Thread
class limits the ability to extend other classes, so implementing Runnable
interface is often preferred, as it allows the class to extend other classes if needed.
Example using Runnable
interface:
public class MyRunnable implements Runnable { public void run() { // code to be executed in the new thread } } Thread thread = new Thread(new MyRunnable()); thread.start();