美文网首页
多线程与锁:(三)synchronized

多线程与锁:(三)synchronized

作者: AmyXYC | 来源:发表于2017-06-15 15:35 被阅读0次

引用自:http://blog.iluckymeeting.com/2018/01/06/threadandlockthree/

什么是synchronized加锁

synchronized是Java语言的关键字,它加的是语言级的锁,被synchronized声明的代码块被加锁后将具有以下特性:

  • 原子互斥性 被synchronized声明的代码块一次只能被一个线程执行,其它线程必须等获得锁的线程执行完成后才能再次加锁执行同步代码块
  • 可见性 锁是加在某一个对象实例上的,如果有多个同步代码块在同一个对象上加锁,则各同步代码块中做的修改将相互可见

在JDK1.6以前synchronized通过对象监视器(Monitor)来加重量级锁,经过JDK1.6的优化引入了偏向锁和轻量级锁,提高了synchronized加锁的效率。

synchronized加锁的优势与不足

  • synchronized加的是非公平锁,效率上优于公平锁,由JVM保证所有申请锁的线程都有机会获得锁
  • synchronized锁的释放是由JVM管理的,即使是同步代码块中抛出了异常,也能保证锁最终会被释放,这样可以避免人为失误造成锁未被释放从而导致死锁
  • synchronized加锁后,JVM在做线程转储时会包含锁信息,这一点对于调试工作非常有帮助
  • 等待获得sychronized锁的线程无法被中断,也不能通过投票获得锁,这将消耗更多的资源来做线程调度

synchronized加锁用法

方式 作用范围 作用对象
代码块 代码块 调用代码块的对象
方法 方法 调用方法的对象
静态方法 静态方法 类的所有对象
括号里的内容 类的所有对象
对象实例 对象本身 具体对象

代码块加锁

public class Demo {

    public void invoke() {
        synchronized (this) {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + " started");
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {

            }
            System.out.println(threadName + " ended");
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            int final_i = i;
            Thread t = new Thread(() -> {
                Demo demo = new Demo();
                Thread.currentThread().setName("thread" + final_i);
                demo.invoke();
            });
            t.start();
        }
    }
}

运行结果如下:

thread0 started
thread1 started
thread2 started
thread2 ended
thread0 ended
thread1 ended

从运行结果上可以看出,3个线程的执行是没有阻塞的,代码块上的synchronized锁没起作用,为什么呢?因为synchronized声明的代码块声明时使用的this对象,所以这个代码块的锁是加在Demo类的对象上的,而这3个线程各自实例化了一个Demo类的对象,每个线程申请的锁都是加在不同对象上的锁,所以不会阻塞。
将上面的代码修改一下,让3个线程申请同一个Demo类实例对象上的锁:

public static void main(String[] args) {
        Demo demo = new Demo();
        for (int i = 0; i < 3; i++) {
            int final_i = i;
            Thread t = new Thread(() -> {
                Thread.currentThread().setName("thread" + final_i);
                demo.invoke();
            });
            t.start();
        }
    }

再次运行一下,结果如下:

thread0 started
thread0 ended
thread2 started
thread2 ended
thread1 started
thread1 ended

可以看出修改后3个线程是依次执行的,synchronized锁生效了

方法加锁

public class Demo {

    public synchronized void invoke() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " started");
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            
        }
        System.out.println(threadName + " ended");
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            int final_i = i;
            Thread t = new Thread(() -> {
                Thread.currentThread().setName("thread" + final_i);
                Demo demo = new Demo();
                demo.invoke();
            });
            t.start();
        }
    }
}
 

运行后的输出:

thread0 started
thread1 started
thread2 started
thread1 ended
thread0 ended
thread2 ended

从输出上可以看出synchronized加锁并没有影响3个线程的执行,为什么呢?因为方法声明上加synchronized锁时,加锁对象是Demo类实例化后的对象,在上面3个线程中每个线程都实例化了一个Demo类的对象,所以锁是加在不同的对象上的,每个线程申请的都是不同的锁,自然不会影响三个线程的执行;将上面的代码修改一下,使3个线程使用同一个Demo类的实例对象,再次运行看一下结果。将main方法修改如下,其它代码不变:

public static void main(String[] args) {
        Demo demo = new Demo();
        for (int i = 0; i < 3; i++) {
            int final_i = i;
            Thread t = new Thread(() -> {
                Thread.currentThread().setName("thread" + final_i);
                demo.invoke();
            });
            t.start();
        }
    }

运行结果如下:

thread0 started
thread0 ended
thread2 started
thread2 ended
thread1 started
thread1 ended

从运行结果上可以看出,3个线程是依次执行的,synchronized加的锁起作用了

静态方法加锁

public class Demo {

    public synchronized static void invoke() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " started");
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {

        }
        System.out.println(threadName + " ended");
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            int final_i = i;
            Thread t = new Thread(() -> {
                Thread.currentThread().setName("thread" + final_i);
                Demo.invoke();
            });
            t.start();
        }
    }
}

运行结果如下:

thread0 started
thread0 ended
thread2 started
thread2 ended
thread1 started
thread1 ended

由结果可以看出3个线程是顺序执行的,这是因为加锁的方法是静态方法,所有的方法调用申请加锁是使用的同一个锁,不论Demo类实例化了多少个对象。

类加锁

还是上面用到的代码块加锁,修改成如下:

public class Demo {

    public void invoke() {
        synchronized (Demo.class) {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + " started");
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {

            }
            System.out.println(threadName + " ended");
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            int final_i = i;
            Thread t = new Thread(() -> {
                Demo demo = new Demo();
                Thread.currentThread().setName("thread" + final_i);
                demo.invoke();
            });
            t.start();
        }
    }
}

运行结果如下:

thread0 started
thread0 ended
thread2 started
thread2 ended
thread1 started
thread1 ended

可以看出3个线程是按顺序执行的,锁生效了,可是3个线程都实例化了一个自己的demo对象,为什么会这样?这是因为加锁的对象变了,

synchronized(this)

这种加锁方式会把锁加在Demo类的实例对象上,如果创建多个Demo类的实例对象就会相应的在每个对象上加锁,而这里用的是

synchronized(Demo.class)

这种加锁方式,此时无论Demo被实例出多少个对象,它们用的都是同一把锁,所以3个线程是顺序执行的。

对象实例加锁

public class Demo {
    private ReentrantLocker lock = new ReentrantLocker();

    public void invoke() {
        synchronized (lock) {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + " started");
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {

            }
            System.out.println(threadName + " ended");
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            int final_i = i;
            Thread t = new Thread(() -> {
                Demo demo = new Demo();
                Thread.currentThread().setName("thread" + final_i);
                demo.invoke();
            });
            t.start();
        }
    }
}

运行结果如下:

thread2 started
thread1 started
thread0 started
thread2 ended
thread1 ended
thread0 ended

可以看出3个线程并没有竞争同一个锁,这是因为每个Demo实例对象都有一个lock对象,所以每个线程都申请了不同的锁;
修改一下代码,将lock对象声明改成下面这样

    private static ReentrantLocker lock = new ReentrantLocker();

再次运行结果如下:

thread0 started
thread0 ended
thread2 started
thread2 ended
thread1 started
thread1 ended

3个线程是按顺序执行的了,为什么呢?因为lock对象被声明成了static静态对象,虽然Demo被实例出了多个对象,但是它们使用的lock对象是同一个,所以3个线程申请的锁是加在同一个对象上的。

相关文章

网友评论

      本文标题:多线程与锁:(三)synchronized

      本文链接:https://www.haomeiwen.com/subject/zkquqxtx.html