Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Multithreading accessing main thread variables/methods

I was testing the following code, and I was wondering how come the threads could access the the increment method?

I was thinking this since thread1 and thread2 are objects created from an anonymous class that don't inherit worker class how can they access the increment() method? what is the theory behind it?

public class Worker {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public void run() {
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                for(int i = 0; i < 10000; i++) {
                    increment();
                }
            }
        });
        thread1.start();

        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                for(int i = 0; i < 10000; i++) {
                    increment();
                }
            }
        });
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Count is: " + count);
    }
}
like image 914
Carlo Luther Avatar asked Dec 29 '25 07:12

Carlo Luther


1 Answers

Since the Runnables are non-static inner classes , the Worker.this is implicitly inherited into the Runnable instances. So that what is really happening is

public void run(){
   Worker.this.increment();
}

If the class were static this wouldn't be the case.

like image 135
John Vint Avatar answered Dec 30 '25 22:12

John Vint



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!