synchronized的类锁和对象锁区别

对象锁:

复制代码
public class ThreadExceptionDemo {

    public static void main(String[] args) throws InterruptedException {


       new Thread(new Runnable() {
           @SneakyThrows
           @Override
           public void run() {
               ThreadExceptionDemo threadExceptionDemo = new ThreadExceptionDemo();
               threadExceptionDemo.int1();
//               int3();

           }
       }).start();
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {

                ThreadExceptionDemo threadExceptionDemo = new ThreadExceptionDemo();
                threadExceptionDemo.int2();
//                int4();
            }
        }).start();


    }

    public synchronized  void  int1() throws InterruptedException {
        System.out.println("int1.........");
        Thread.sleep(5000);
    }

    public synchronized  void  int2() throws InterruptedException {
        System.out.println("int2.........");
        Thread.sleep(5000);
    }


    public synchronized static void  int3() throws InterruptedException {
        System.out.println("int3.........");
        Thread.sleep(5000);
    }

    public synchronized static void  int4(){
        System.out.println("int4.........");
    }
}
 
复制代码

结果:对象锁会同时获取到锁

int1.........
int2.........

 

类锁:

复制代码
public class ThreadExceptionDemo {

    public static void main(String[] args) throws InterruptedException {

       new Thread(new Runnable() {
           @SneakyThrows
           @Override
           public void run() {
//               ThreadExceptionDemo threadExceptionDemo = new ThreadExceptionDemo();
//               threadExceptionDemo.int1();
               int3();

           }
       }).start();
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {

//                ThreadExceptionDemo threadExceptionDemo = new ThreadExceptionDemo();
//                threadExceptionDemo.int2();
                int4();
            }
        }).start();


    }

    public synchronized  void  int1() throws InterruptedException {
        System.out.println("int1.........");
        Thread.sleep(5000);
    }

    public synchronized  void  int2() throws InterruptedException {
        System.out.println("int2.........");
        Thread.sleep(5000);
    }


    public synchronized static void  int3() throws InterruptedException {
        System.out.println("int3.........");
        Thread.sleep(5000);
    }

    public synchronized static void  int4(){
        System.out.println("int4.........");
    }
}
 
复制代码

结果:(in3输出后延迟5秒输出int4)

int3.........
int4.........

 

并发情况下,类锁需要等持有线程释放锁才可以,获取资源,

 

posted @   不死码农  阅读(217)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2019-06-10 Java的三种代理模式
点击右上角即可分享
微信分享提示