C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programming language

Thread Synchronisation in Java with Example

In this article, we are going to learn about the Thread synchronisation? Explaining through an example with and without thread synchronisation.
Submitted by Aman Gautam, on January 05, 2018

In the multithreaded programming, multiple threads run simultaneously and access common resources. To prevent deadlock, we must ensure that a resource must be shared by one thread at a time or else it may produce a weird or unforeseen result. This process is known as Synchronization. In this article, we will discuss how to achieve thread synchronization in java?

Let us understand this by taking an example. There are two threads which are accessing and writing to common file output.txt. If no synchronization is used then, one thread writes few words in the file and meanwhile another thread starts writing to the file. The resulting file will contain random contents written by both threads. With synchronization, if one thread is writing to the file, the file will be locked (in LOCK mode) and no other thread or process can access it until first thread completed its work.

Consider the code, without synchronisation,

class print{
     public void printMSG(String s){
        for(int i=1;i<=5;i++) {
            System.out.println(s);
            try {
                Thread.sleep(1000);        // used to sleep current execution for 1s
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}
class one extends Thread{
    print t;
    one(print t){
        this.t=t;
    }
    public void run(){
       t.printMSG("Hi");
    }
}
class two extends Thread{
    print t;
    two(print t){
        this.t=t;
    }

    public void run() {
        t.printMSG("Bye");
    }
}


public class ExSynchronization {
    public static void main(String[] args) {
        print t=new print();
        one ob=new one(t);
        two o2=new two(t);
        ob.start();
        o2.start();
    }
}

Output

Hi
Bye
Bye
Hi
Hi
Bye
Hi
Bye
Hi
Bye

Note: This output is random.

In this program, we have designed two thread which are accessing a common function printMSG(). When we run this code, we may get the unwanted output as seen above.

To synchronise the output we will use synchronized method. This will lock the object for a shared resource. We can do this by adding synchronized keyword to the shared method.

Let see the synchronized code below,

class print{
     synchronized public void printMSG(String s){
        for(int i=1;i<=5;i++) {
            System.out.println(s);
            try {
                Thread.sleep(1000);     // used to sleep current execution for 1s
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}
class one extends Thread{
    print t;
    one(print t){
        this.t=t;
    }
    public void run(){
       t.printMSG("Hi");
    }
}
class two extends Thread{
    print t;
    two(print t){
        this.t=t;
    }

    public void run() {
        t.printMSG("Bye");
    }
}


public class ExSynchronization {
    public static void main(String[] args) {
        print t=new print();
        one ob=new one(t);
        two o2=new two(t);
        ob.start();
        o2.start();
    }
}

Output

Hi
Hi
Hi
Hi
Hi
Bye
Bye
Bye
Bye
Bye

Note: The threads may start in either order.



Advertisements




Liked this article? Do share with your friends :)


COMMENTS