Java面试题2:多线程与synchronized

来源:互联网 发布:淘宝联盟qq群推广步揍 编辑:程序博客网 时间:2024/05/21 17:39

2 有一个静态变量num,初始值为0。现在开了1000个线程,每个线程内循环1000次,每循环对num自加1,问最后的值是大于、等于还是小于1000000?
答:
(1)小于1000000,因为有1000个线程,不同的线程有可能同时访问num,导致自加的次数变少。

import java.util.concurrent.TimeUnit;public class Test implements Runnable{    private static int num = 0;    @Override    public void run() {        for(int i = 1; i <=1000; i++){            num++;            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:"+i);            thread.start();        }        try {            // 等待全部子线程执行完毕            TimeUnit.SECONDS.sleep(30);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("Finally, num = " + num);    }}

运行结果:
Thread:19, num = 999981
Thread:19, num = 999982
Thread:19, num = 999983
Thread:975, num = 999367
Thread:975, num = 999984
Thread:975, num = 999985
Thread:975, num = 999986
Thread:975, num = 999987
Thread:975, num = 999988
Thread:975, num = 999989
Thread:975, num = 999990
Finally, num = 999990

(2)若要防止此现象,要用static synchronized关键字对数据进行同步保护。

import java.util.concurrent.TimeUnit;public class Test implements Runnable{    private static int num = 0;    static synchronized 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:"+i);            thread.start();        }        try {            // 等待全部子线程执行完毕            TimeUnit.SECONDS.sleep(30);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("Finally, num = " + num);    }}

运行结果:
Thread:3, num = 999993
Thread:3, num = 999994
Thread:3, num = 999995
Thread:3, num = 999996
Thread:3, num = 999997
Thread:3, num = 999998
Thread:3, num = 999999
Thread:3, num = 1000000
Thread:788, num = 999985
Finally, num = 1000000