Search code examples
javamultithreadingconcurrencyjava-threadsthread-sleep

How to synchronize Java thread as a nested class?


when I was reading about different ways of defining threads in Java, I can't able to synchronize Thread as a nested class. This is the code.

class OuterClass {

int count = 0;

InnerClass in[];

OuterClass() {

    in = new InnerClass[4];

    for (int i = 0; i < 4; i++) {

        in[i] = new InnerClass();
    }
}

public void startFun() throws Exception{

    for (int i = 0; i < 4; i++) {

        in[i].start();
    }

    for (int i = 0; i < 4; i++)
        in[i].join();
}
public static void main(String[] agrs) throws Exception {

    OuterClass oc = new OuterClass();
    oc.startFun();
}

class InnerClass extends Thread {

    public synchronized void run() {

        count ++;
        System.out.println(count);
    }
}}

How to synchronize count variable in this program by using thread as a nested class? Because I used this model in my project. Output for the above program was:

output:
1
4
3
2

How to synchronize and get the output as:

1
2
3
4

Solution

  • You have 4 different objects (and 4 different monitors for locking) for synchronization (InnerClass1, InnerClass2 etc). For synchronization of all your threads, you should use one object (one monitor) for example:

    class OuterClass {
    
    Object ob = new Object();
    
    volatile int count = 0;
    
    InnerClass in[];
    
    OuterClass() {
    
        in = new InnerClass[4];
    
        for (int i = 0; i < 4; i++) {
            in[i] = new InnerClass();
        }
    }
    
    public void startFun() throws Exception{
    
        for (int i = 0; i < 4; i++) {
            in[i].start();
        }
    
        for (int i = 0; i < 4; i++)
            in[i].join();
    }
    public static void main(String[] agrs) throws Exception {
    
        OuterClass oc = new OuterClass();
        oc.startFun();
    }
    
    class InnerClass extends Thread {
    
        public void run() {
            synchronized (ob){
                count ++;
                System.out.println(count);
            }
        }
    }}
    

    also, your shared field should be volatile.