Why is there a difference in output? I have 2 cases:
- In first case I use static functions
f1
andf2
:
Here is my main method body:public static synchronized void f1() { for (int i = 0; i < 100; i++) System.out.print("A"); } public static synchronized void f2() { for (int i = 0; i < 100; i++) System.out.print("B"); }
the output is:Thread t1 = new Thread( new Runnable(){public void run(){f1();}} ); Thread t2 = new Thread( new Runnable(){public void run(){f2();}} ); t1.start(); t2.start();
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
- In the second case
f1
andf2
are not static:
the output is so messy:public synchronized void f1() { for (int i = 0; i < 100; i++) System.out.print("A"); } public synchronized void f2() { for (int i = 0; i < 100; i++) System.out.print("B"); }
AAABABABBBBAAAAAAAAAABBAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBAA