目的

本文只针对synchronized的使用进行描述以及代码演示。具体原理不做深入探讨

简介

synchronized 在多线程并发环境下,通过加锁的形式保证了数据的一致性,锁存在Java对象头里。如果对象是数组类型,则虚拟机用3个Word(字宽)存储对象头,如果对象是非数组类型,则用2字宽存储对象头。在32位虚拟机中,一字宽等于四字节,即32bit。

对象锁、代码块锁的使用

先看一段示例代码

代码块一

public class T {

    private Integer count = 0;
    private Object o = new Object();

    public void m() {
        //任何线程要执行下面的代码,必须先拿到o的锁
        synchronized (o) {
            for (int i = 0; i < 100000; i++) {
                count++;
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        // 采用 CountDownLatch 保证了所有线程同时开始,同时结束
        CountDownLatch start = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(10);
        T t = new T();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    start.await();
                    t.m();
                } catch (InterruptedException e) {
                    e.printStackTrace();

                } finally {
                    end.countDown();
                }

            }).start();
        }
        start.countDown();
        end.await();
        System.out.println(Thread.currentThread().getName() + " count = " + t.count);
    }
}

输出结果:
main count = 1000000
结果正确。

结论:我们在多线程并发环境下,为了保证所有线程对某个对象、基本类型的操作保持唯一性,需要去拿到一个全局不变的唯一锁,只有锁对象不变才能保证计算变量的唯一性。

以上写法还可以直接锁当前对象不需要new 一个object

代码块二

public class T {

    private Integer count = 0;
    public void m() {
        //任何线程要执行下面的代码,必须先拿到当前对象的锁
        //锁的是当前对象
        synchronized (this) {
            for (int i = 0; i < 100000; i++) {
                count++;
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        // 采用 CountDownLatch 保证了所有线程同时开始,同时结束
        CountDownLatch start = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(10);
        T t = new T();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    start.await();
                    t.m();
                } catch (InterruptedException e) {
                    e.printStackTrace();

                } finally {
                    end.countDown();
                }

            }).start();
        }
        start.countDown();
        end.await();
        System.out.println(Thread.currentThread().getName() + " count = " + t.count);
    }
}

上面的代码 还可以直接在m 方法上加锁,同样锁的是当前对象,如下代码

代码块三

public class T {

    private Integer count = 0;

    public synchronized void m() {
        //任何线程要执行下面的代码,必须先拿到当前对象的锁
        //锁的是当前对象
        for (int i = 0; i < 100000; i++) {
            count++;
        }
    }


    public static void main(String[] args) throws InterruptedException {
        // 采用 CountDownLatch 保证了所有线程同时开始,同时结束
        CountDownLatch start = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(10);
        T t = new T();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    start.await();
                    t.m();
                } catch (InterruptedException e) {
                    e.printStackTrace();

                } finally {
                    end.countDown();
                }

            }).start();
        }
        start.countDown();
        end.await();
        System.out.println(Thread.currentThread().getName() + " count = " + t.count);
    }
}

此代码块与代码块2 一样,锁的都是当前对象,代码块1为可自由锁定根据实际情况定的对象,一般采用代码块1 的方法进行代码块的锁定,这样减少了锁定的范围提高了代码的性能。通俗理解只要保证每次拿到的是同一个锁即可,对象变了锁也就变了。

**
**

以下代码为错误的例子

public class T {

    private Integer count = 0;

    public void m() {
        //任何线程要执行下面的代码,必须先拿到当前对象的锁
        //锁的是当前对象
        synchronized (count) {
            for (int i = 0; i < 100000; i++) {
                count++;

            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        // 采用 CountDownLatch 保证了所有线程同时开始,同时结束
        CountDownLatch start = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(10);
        T t = new T();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    start.await();
                    t.m();
                } catch (InterruptedException e) {
                    e.printStackTrace();

                } finally {
                    end.countDown();
                }

            }).start();
        }
        start.countDown();
        end.await();
        System.out.println(Thread.currentThread().getName() + " count = " + t.count);
    }
}

输出结果:
main count = 185200  错误的结果,我们想要的是 1000000
posted on 2021-06-30 22:13  XIN1024  阅读(236)  评论(0)    收藏  举报