Try executing this code:
class Test extends Thread { Test(String name) { super(name); } int x = 0, y = 0; int addX() {x++; return x;} int addY() {y++; return y;} public void run() { for(int i = 0; i < 10; i++) System.out.println(addX() + " " + addY() + ", name:" + getName()); } public static void main(String args[]) { Test run1 = new Test("thread1"); Test run2 = new Test("thread2"); run1.start(); run2.start(); } }
You will get a result similar to this:
1 1, name:thread2 2 2, name:thread2 1 1, name:thread1 2 2, name:thread1 3 3, name:thread2 3 3, name:thread1
This is because protectors are not executed synchronously. You do not know when this will be done. In your code, 1 1 , and then again 1 1 - this is just the output of two threads performing the same thing.
source share