• November 21, 2024

How to Implement Concurrency in Java?

Concurrency in programming is the ability to run multiple tasks simultaneously in a program. Concurrency allows for better utilization of system resources and can improve program performance. In Java, concurrency can be achieved using threads. Here is an example code in Java that demonstrates concurrency using threads:

public class MyThread extends Thread {
    private String name;
    
    public MyThread(String name) {
        this.name = name;
    }
    
    public void run() {
        System.out.println("Thread " + name + " is running.");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread("Thread 1");
        MyThread t2 = new MyThread("Thread 2");
        MyThread t3 = new MyThread("Thread 3");
        
        t1.start();
        t2.start();
        t3.start();
    }
}

In this example, we define a class called MyThread that extends the Thread class in Java. The MyThread class takes a name parameter in its constructor and overrides the run() method to print out a message indicating that the thread is running.

In the Main class, we create three instances of MyThread and start them using the start() method. When the program runs, all three threads will start running simultaneously and print out their respective messages. This demonstrates concurrency in Java, as multiple threads are running simultaneously.

Leave a Reply

Your email address will not be published. Required fields are marked *