Android sychronized关键字理解,并发问题

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                testAdd(1);
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                testAdd(2);
            }
        });
        thread1.start();
        thread2.start();
    }

    private static void testAdd(int type) {
        for (int i = 0; i < 10000; i++) {
            a++;
        }
        System.out.print("线程" + type + "、a:" + a);
    }

上面是2个线程,执行的是同一个方法,a++,这时候加10000万次,结果

“线程1、a:10000线程 2、a:20000
Process finished with exit code 0”

当i是10万的时候呢?本应该打印相加应该是10万,20万,但是它却达不到预期的,就这是并发的现象,达不到预期值,怎么解决?

方法1、加“synchronized”关键字

    private static synchronized void testAdd(int type) {
        for (int i = 0; i < 100000; i++) {
            a++;
        }
        System.out.print("线程" + type + "、a:" + a);
    }

运行结果:

线程2、a:100000线程1、a:200000
Process finished with exit code 0

 

方法2、使用ReentrantLock类,如下:

    private static  void testAdd(int type) {
        for (int i = 0; i < 100000; i++) {
            lock.lock();
            try{
                a++;
            } finally {
                lock.unlock();
            }
        }
        System.out.print("线程" + type + "、a:" + a);
    }

这里的lock.lock()和lock.unlock();要一一对应,并且try和finally也是要一一对应;

 

 

 

你可能感兴趣的:(高级开发课件)