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 @ 2022-06-10 18:27  不死码农  阅读(212)  评论(0编辑  收藏  举报