This code has no inner classes:
class Threads1 implements Runnable { int x = 0; public void run(){ int current = 0; for(int i = 0; i<4; i++){ current = x; System.out.println(current + ", "); x = current + 2; } } } public class b{ public static void main(String[] args) { Runnable r1 = new Threads1(); new Thread(r1).start(); new Thread(r1).start(); } } OUTPUT :
0, 2, 0, 4, 6, 2, 4, 6 This code uses an inner class called "Runner":
public class Threads1 { int x = 0; public class Runner implements Runnable { public void run(){ int current = 0; for(int i = 0; i<4;i++){ current = x; System.out.println(current + ", "); x = current + 2; } } } public static void main(String[] args) { new Threads1().go(); } public void go(){ Runnable r1 = new Runner(); new Thread(r1).start(); new Thread(r1).start(); } } OUTPUT : (0, 2, 4, 4, 6, 8, 10, 6,) or (0, 2, 4, 6, 8, 10, 12, 14,)
I learned that when two threads are created , they work on their own stacks, which means they share nothing with each other i.e output ( 0, 2, 0, 4, 6, 2, 4, 6) might be from ( T1, T1, T2, T1, T1 ,T2, T2, T2) where T1 AND T2 are Thread 1 and Thread 2.
However , when I used run() in the inner class, both threads share the Current variable with each other. For example output (0, 2, 4, 4, 6, 8, 10, 6,) might be from (T1 ,T1, T1 ,T2 ,T2, T2, T2, T1). As you can see, there is double a 4 in the output which means thread1 handed over its value to thread2. Why is that so?