Multithreading is an important concept in Java that allows multiple threads
to execute concurrently within a single program. It is particularly useful
for applications that need to handle multiple tasks or processes at the
same time.
Here is a basic example of multithreading in Java:
1. Create a class that extends the Thread class or implements the
Runnable interface. This class will define the code that will run in parallel.
java
public class MyThread extends Thread {
@Override
public void run() {
// Code to be executed in parallel
2. Create an instance of the thread class and start the thread using the
`start()` method.
java
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
[Link]();
3. The `run()` method in the thread class will be executed concurrently
with the main thread. You can add any code or logic within the `run()`
method that you want to execute concurrently.
java
public class MyThread extends Thread {
@Override
public void run() {
// Code to be executed in parallel
for (int i = 0; i < 5; i++) {
[Link]("Thread: " + i);
4. You can also create multiple threads and start them concurrently.
java
public class Main {
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
[Link]();
[Link]();
In this example, both `myThread1` and `myThread2` will execute
concurrently and print the numbers from 0 to 4.