Java interview questions 2: multi threading and synchronized

2 has a static variable, num, with an initial value of 0. Now open 1000 threads, each thread within 1000 cycles, each cycle to num plus 1, ask the final value is greater than, equal to or less than 1000000?
answer:
(1) less than 1000000, because there are 1000 threads, different threads may access num at the same time, resulting in less than the number of self increasing.

Import java.util.concurrent.TimeUnit; public class Test implements Runnable{private static int num @Override public = 0; void (run) {for (int i = 1; I < =1000; i++) {num++; System.out.println (Thread.currentThread) (.GetName) ("num + =" + Num);}} (main void public static String[] args throws InterruptedException for (int) {I = 1; I < =1000; i++) {Thread thread = new Thread (New) (Test); thread.setName ("Thread:"); thread.start (+i);} try {/ / wait for all Zi Xiancheng completed TimeUnit.SECONDS.sleep (30) catch (InterruptedException E;} {(e.printStackTrace)); } System.out.println ("Finally, Num =" + Num)}}

Results:
Thread:19, num
Thread:19 = 999981, Num = 999982
Thread:19
Thread:975, Num = 999983, Num = 999367
Thread:975
Thread:975, Num = 999984, Num = 999985
Thread:975
Thread:975, Num = 999986, Num = 999987
Thread:975
Thread:975, Num = 999988, Num = 999989
Thread:975
Finally, Num = 999990, Num = 999990

(2) if you want to prevent this phenomenon, use the static synchronized keyword to synchronize the data protection.

Import java.util.concurrent.TimeUnit; public class Test implements Runnable{private static int num static synchronized = 0; private void increaseNumber (num++) {}; @Override public void (run) {for (int i = 1; I < =1000; i++) {(increaseNumber); System.out.println (Thread.currentThread) (.GetName (Num) + ". =" + Num);}} public static void main (String[] args throws InterruptedException for (int) {I = 1; I < =1000; i++) {Thread thread = new Thread (New) (Test); thread.setName ("Thread:"); thread.start (+i);} try {/ / wait for all Zi Xiancheng finished TimeUnit.SE CONDS.sleep (30);} catch (InterruptedException, e) {e.printStackTrace ();} System.out.println (` Finally ',' num = '+ Num)}}

Results:
Thread:3, num
Thread:3 = 999993, Num = 999994
Thread:3
Thread:3, Num = 999995, Num = 999996
Thread:3
Thread:3, Num = 999997, Num = 999998
Thread:3
Thread:3, Num = 999999, Num = 1000000
Thread:788
Finally, Num = 999985, Num = 1000000