Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Wednesday, April 9, 2025

Synchronizing threads.



Program: 


// Example of thread synchronization using synchronized method

class SharedResource 

{

    // Synchronized method to ensure thread safety

    synchronized void printNumbers(int n) {

        for (int i = 1; i <= 5; i++) {

            System.out.println(n * i);

            try {

                Thread.sleep(500); // Simulating some processing time

            } catch (InterruptedException e) {

                System.out.println(e);

            }

        }

    }

}


// Thread class that works on SharedResource

class MyThread extends Thread

 {

    SharedResource resource;

    int num;


    MyThread(SharedResource resource, int num) {

        this.resource = resource;

        this.num = num;

    }


    public void run() 

{

        resource.printNumbers(num); // Calling synchronized method

    }

}


// Main class

public class ThreadSyncExample {

    public static void main(String[] args) {

        SharedResource obj = new SharedResource(); // Shared object


        MyThread t1 = new MyThread(obj, 5);

        MyThread t2 = new MyThread(obj, 10);


        t1.start();

        t2.start();

    }

}


 

No comments:

Post a Comment