Name:Vitthal Misal
Reg No:21BCE11292
JAVA Multithreading Assignment
Q.How can you create a thread in Java, and what are the different ways to do it . Explain with simple code examples
In Java, you can create a thread by extending the Thread class or implementing the Runnable interface. Here are
examples of both approaches:
1.Extending the Thread class:
class MyThread extends Thread {
public void run() {
// Code to be executed by the thread
for (int i = 0; i < 5; i++) {
System.out.println("Thread: " + i);
try {
Thread.sleep(1000); // Simulate some work being done
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Start the thread
2.Implementing the Runnable interface:
class MyRunnable implements Runnable {
public void run() {
// Code to be executed by the thread
for (int i = 0; i < 5; i++) {
System.out.println("Thread: " + i);
try {
Thread.sleep(1000); // Simulate some work being done
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // Start the thread
Both approaches will create a separate thread of execution that will run concurrently with the main thread. The run()
method contains the code that will be executed by the thread. You can customize this method to perform any task
you need.
Both examples demonstrate how to create a thread in Java:
1. **Extending the `Thread` class**:
- Define a class that extends the `Thread` class.
- Override the `run()` method with the code to be executed by the thread.
- Instantiate an object of your custom thread class and call `start()` to begin execution.
2. **Implementing the `Runnable` interface**:
- Define a class that implements the `Runnable` interface.
- Implement the `run()` method with the code to be executed by the thread.
- Instantiate a `Thread` object, passing an instance of your `Runnable` class to its constructor.
- Call `start()` on the `Thread` object to start execution.
In both cases, the `run()` method contains the code to be executed by the thread. When `start()` is called, the JVM
spawns a new thread of execution, and the `run()` method of your thread or runnable object is invoked on that
thread.