This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Thursday, March 2, 2023

Explain the multithreaded programming in java with example.

 Multithreading is a powerful feature in Java that allows you to write programs that can execute multiple threads simultaneously. This can help improve the performance of your applications by utilizing the full power of modern multi-core processors.

Here's an example of how multithreading works in Java:

public class MyThread implements Runnable {
    public void run() {
        System.out.println("Thread started: " + Thread.currentThread().getName());
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Thread finished: " + Thread.currentThread().getName());
    }
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        Thread t1 = new Thread(thread1, "Thread 1");
        Thread t2 = new Thread(thread2, "Thread 2");
        t1.start();
        t2.start();
    }
}

In this example, we define a class called MyThread that implements the Runnable interface. The run() method contains the code that will be executed when the thread is started. In this case, we simply print some messages to the console and pause the thread for 100 milliseconds using the Thread.sleep() method.

In the main() method, we create two instances of the MyThread class and wrap them in Thread objects. We give each thread a name using the setName() method. We then start the threads using the start() method. This causes the run() method of each thread to be executed simultaneously.

When you run this program, you will see that the output from the two threads is interleaved, which demonstrates how they are executing simultaneously. This program is a simple example, but in real-world applications, multithreading can be used to perform time-consuming tasks in the background while the main thread of the program continues to respond to user input or perform other tasks.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget