synchroized锁的使用注意事项

    技术2026-01-11  10

    Synchronized使用注意事项

     代码块的形式

    (1)使用到Synchronized锁的时候可以使用任意对象作为锁。

      

    Object obj = new Object(); public void test(){ synchronized (obj){ try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } }

    (2)如果在方法上加上Synchroized关键字默认使用this锁。

    public void test(){ synchronized (this){ try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } }

    注意:如果方法是一个静态方法的情况下,就使用当前类的cass字节码作为锁。

    public class Test004 { public static void test(){ synchronized (Test004.class){ try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } }

     

     

     

    Processed: 0.033, SQL: 9