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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With