zoukankan      html  css  js  c++  java
  • 关于Synchronized(二)

    一.synchronized 的用法分类

    Java中每一个对象都可以作为锁,这是synchronized实现同步的基础:

    1、普通同步方法(实例方法),锁是当前实例对象 ,进入同步代码前要获得当前实例的锁

    2、静态同步方法,锁是当前类的class对象 ,进入同步代码前要获得当前类对象的锁

    3、同步方法块,锁是括号里面的对象,对给定对象加锁,进入同步代码库前要获得给定对象的锁。

    二.synchronized 的用法详解

    1、synchronized作用于实例方法

    (1)多个线程访问同一个对象的同一个方法:

    public class synchronizedTest implements Runnable {
        //共享资源
        static int i =0;
        /**
         * synchronized 修饰实例方法
         */
        public synchronized void increase(){
            i++;
        }
    @Override
    public void run(){ for (int j =0 ; j<10000;j++){ increase(); } } public static void main(String[] args) throws InterruptedException { synchronizedTest test = new synchronizedTest(); Thread t1 = new Thread(test); Thread t2 = new Thread(test); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(i); } }

    结果:

    2000

    分析:当两个线程同时对一个对象的一个方法进行操作,只有一个线程能够抢到锁。因为一个对象只有一把锁,一个线程获取了该对象的锁之后,

    其他线程无法获取该对象的锁,就不能访问该对象的其他synchronized实例方法,但是可以访问非synchronized修饰的方法。

    (2)一个线程获取了该对象的锁之后,其他线程来访问其他synchronized实例方法现象:
    public class SynchronizedTest {
    public synchronized void method1() { System.out.println("Method 1 start"); try { System.out.println("Method 1 execute"); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 1 end"); } public synchronized void method2() { System.out.println("Method 2 start"); try { System.out.println("Method 2 execute"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 2 end"); } public static void main(String[] args) { final SynchronizedTest test = new SynchronizedTest(); new Thread(test::method1).start(); new Thread(test::method2).start(); } }

    结果:

    Method 1 start
    Method 1 execute
    Method 1 end
    Method 2 start
    Method 2 execute
    Method 2 end

    分析:可以看出其他线程来访问synchronized修饰的其他方法时需要等待线程1先把锁释放。

    (3)一个线程获取了该对象的锁之后,其他线程来访问其他非synchronized实例方法现象 

    去掉(2)中方法二的synchronized

    public class SynchronizedTest {
    public synchronized void method1() { System.out.println("Method 1 start"); try { System.out.println("Method 1 execute"); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 1 end"); } public void method2() { System.out.println("Method 2 start"); try { System.out.println("Method 2 execute"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 2 end"); } public static void main(String[] args) { final SynchronizedTest test = new SynchronizedTest(); new Thread(test::method1).start(); new Thread(test::method2).start(); } }

    结果:

    Method 1 start
    Method 1 execute
    Method 2 start
    Method 2 execute
    Method 2 end
    Method 1 end

    分析:当线程1还在执行时,线程2也执行了,所以当其他线程来访问非synchronized修饰的方法时是可以访问的。

    (4)当多个线程作用于不同的对象

    public class SynchronizedTest {
    public synchronized void method1() { System.out.println("Method 1 start"); try { System.out.println("Method 1 execute"); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 1 end"); } public synchronized void method2() { System.out.println("Method 2 start"); try { System.out.println("Method 2 execute"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 2 end"); } public static void main(String[] args) { final SynchronizedTest test1 = new SynchronizedTest(); final SynchronizedTest test2 = new SynchronizedTest(); new Thread(test1::method1).start(); new Thread(test2::method2).start(); } }

    结果:

    Method 1 start
    Method 1 execute
    Method 2 start
    Method 2 execute
    Method 2 end
    Method 1 end

    分析:因为两个线程作用于不同的对象,获得的是不同的锁,所以互相并不影响

    2、synchronized作用于静态方法

    public class synchronizedTest implements Runnable {
    //共享资源 static int i =0; /** * synchronized 修饰实例方法 */ public static synchronized void increase(){ i++; } @Override public void run(){ for (int j =0 ; j<10000;j++){ increase(); } } public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new synchronizedTest()); Thread t2 = new Thread(new synchronizedTest()); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(i); }

    结果:

    20000

    分析:

    由例子可知,两个线程实例化两个不同的对象,但是访问的方法是静态的,两个线程发生了互斥(即一个线程访问,另一个线程只能等着),

    因为静态方法是依附于类而不是对象的,当synchronized修饰静态方法时,锁是class对象。

    3、synchronized作用于同步代码块

    为什么要同步代码块呢?在某些情况下,我们编写的方法体可能比较大,同时存在一些比较耗时的操作,而需要同步的代码又只有一小部分,

    如果直接对整个方法进行同步操作,可能会得不偿失,此时我们可以使用同步代码块的方式对需要同步的代码进行包裹,这样就无需对整个方法进行同步操作了。

    public class synchronizedTest implements Runnable {
    static synchronizedTest instance=new synchronizedTest();
    static int i=0;
    @Override
    public void run() { //省略其他耗时操作.... //使用同步代码块对变量i进行同步操作,锁对象为instance synchronized(instance){ for(int j=0;j<10000;j++){ i++; } } } public static void main(String[] args) throws InterruptedException { Thread t1=new Thread(instance); Thread t2=new Thread(instance); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(i); } }

    结果:

    20000

    分析:

    将synchronized作用于一个给定的实例对象instance,即当前实例对象就是锁对象,每次当线程进入synchronized包裹的代码块时就会要求当前线程持有instance实例对象锁,

    如果当前有其他线程正持有该对象锁,那么新到的线程就必须等待,这样也就保证了每次只有一个线程执行i++;操作。

    当然除了instance作为对象外,我们还可以使用this对象(代表当前实例)或者当前类的class对象作为锁,如下代码:

    //this,当前实例对象锁
    synchronized(this){
        for(int j=0;j<1000000;j++){
            i++;
        }
    }
    
    //class对象锁
    synchronized(AccountingSync.class){
        for(int j=0;j<1000000;j++){
            i++;
        }
    }

    三.总结

    (1)无论synchronized关键字加在方法上还是对象上,如果它作用的对象是非静态的,则它取得的锁是对象;

    如果synchronized作用的对象是一个静态方法或一个类,则它取得的锁是对类,该类所有的对象同一把锁。

    (2)每个对象只有一个锁(lock)与之相关联,谁拿到这个锁谁就可以运行它所控制的那段代码。

    (3)实现同步是要很大的系统开销作为代价的,甚至可能造成死锁,所以尽量避免无谓的同步控制。

    (4)synchronized关键字不能继承。对于父类中的 synchronized 修饰方法,子类在覆盖该方法时,默认情况下不是同步的,必须显示的使用 synchronized 关键字修饰才行。

    (5)在定义接口方法时不能使用synchronized关键字。

    (6)构造方法不能使用synchronized关键字,但可以使用synchronized代码块来进行同步。



  • 相关阅读:
    【Android-音乐类】音友 免费下载、试听、全网最全的音乐 还不快来白嫖~
    数据结构 10 基础数据结构 二叉堆 堆排序算法详解
    数据结构 9 基础数据结构 二叉堆 了解二叉堆的元素插入、删除、构建二叉堆的代码方式
    数据结构 8 基础排序算法详解、快速排序的实现、了解分治法
    Jenkins+tomcat自动发布的热部署/重启及遇到的坑解决办法
    Spring笔记(3)
    多线程高并发编程(12) -- 阻塞算法实现ArrayBlockingQueue源码分析
    多线程高并发编程(11) -- 非阻塞算法实现ConcurrentLinkedQueue源码分析
    多线程高并发编程(10) -- ConcurrentHashMap源码分析
    Spring笔记(1)
  • 原文地址:https://www.cnblogs.com/ZJOE80/p/12870610.html
Copyright © 2011-2022 走看看