Java Assignment
Java Assignment
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:
try {
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
try {
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
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:
- 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.
- 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.
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.