I have created 3 threads which are accessing inner class MyInnerClass of ThreadsAroundInnerClasses outer class.
package com.test;
public class ThreadsAroundInnerClasses {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread(), "THREAD-1");
Thread t2 = new Thread(new MyThread(), "THREAD-2");
Thread t3 = new Thread(new MyThread(), "THREAD-3");
t1.start();
t2.start();
t3.start();
}
static class MyInnerClass {
static int counter = 0;
public void printIt(String threadName) {
System.out.println("I am inside inner class, counter value is " + ++counter + " and thread name is " + threadName);
}
}
}
class MyThread implements Runnable {
@Override
public void run() {
ThreadsAroundInnerClasses.MyInnerClass innerObj = new ThreadsAroundInnerClasses.MyInnerClass();
innerObj.printIt(Thread.currentThread().getName());
}
}
In the output I can see that counter static variable in MyInnerClass class is not getting updated in sequential order.
I am inside inner class, counter value is 1 and thread name is THREAD-1 I am inside inner class, counter value is 3 and thread name is THREAD-2 I am inside inner class, counter value is 2 and thread name is THREAD-3
It would be of great help if someone can explain how inner classes are handle in case of multithreading? Can we synchronize whole inner class?
Thanks in advance for the help.