Creating Threads in Java
Multithreading in Java is a feature that allows concurrent execution of two or more parts of a program to maximize the utilization of the CPU. Each part of such a program is called a thread, and the process of executing multiple threads simultaneously is called multithreading.
In Java, there are two main ways to create a thread:
- By extending the
Thread
class - By implementing the
Runnable
interface
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
try {
Thread.sleep(1000); // sleep for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
Explanation
Extending the
Thread
class:- A class is created that extends
Thread
. - The
run()
method is overridden to define the code that constitutes the new thread. - An instance of the class is created and the
start()
method is called to begin execution.
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
try {
Thread.sleep(1000); // sleep for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
t1.start();
t2.start();
}
}
Explanation
Implementing the Runnable interface:
- A class implements the
Runnable
interface. - The
run()
method is overridden to define the thread's code. - An instance of
Thread
is created, passing theRunnable
instance to theThread
constructor. - The
start()
method is called to begin execution.
In both examples, the
run()
method contains a loop that prints the current thread's ID and a value, then sleeps for one second to simulate a time-consuming task. The start()
method is called on each thread to begin their execution
Comments
Post a Comment