synchronize关键字

一:synchronized关键字,代表这个方法加锁,相当于不管哪一个线程(例如线程A),运行到这个方法时,都要检查有没有其它线程B(或者C、D等)正在用这个方法,若有则要等正在使用synchronized方法的线程B(或者C、D)运行完这个方法后再运行此线程A,若没有则直接运行。

 

二:synchronized静态方法与非静态方法的区别

(1):在加了synchronize的静态方法中锁的是本类。

(2):在加了synchronize的非静态方法中锁的是调用的对象

 

三:代码实现

(1):

public class Test {
    public static void main(String[] args) {
               Test test=new Test();
               new Thread(
                      ()->{
                          test.func();
                          },"A"
                      ).start();
               new Thread(
                      ()->{test.func2();}
                      ,"B").start();
    }

    public synchronized void func(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread()+":非静态!!!!!!!!!!!");

    }
    public synchronized  void func2(){
        System.out.println(Thread.currentThread()+"非静态-------------------------");
    }
}

 

 此时我们可以看到,两个方法是同时出现的,因为加了synchronize的非静态方法锁的是调用这个方法的对象,所以func2排队等待func执行。

(2):

public class Test {
    public static void main(String[] args) {
               Test test=new Test();
               Test test1=new Test();
              new Thread(
                      ()->{
                          test.func();
                          },"A"
                      ).start();
              new Thread(
                      ()->{test1.func2();}
                      ,"B").start();
    }

    public synchronized void func(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread()+":非静态!!!!!!!!!!!");

    }
    public synchronized  void func2(){
        System.out.println(Thread.currentThread()+"非静态-------------------------");
    }
}

 

因为方法调用的对象不同,所以func2比func先执行

(3)

 

public class Test {
    public static void main(String[] args) {
               Test test=new Test();
               Test test1=new Test();
              new Thread(
                      ()->{
                          test.func();
                          },"A"
                      ).start();
              new Thread(
                      ()->{test1.func2();}
                      ,"B").start();
    }

    public synchronized  static void func(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread()+":非静态!!!!!!!!!!!");

    }
    public synchronized  static void func2(){
        System.out.println(Thread.currentThread()+"非静态-------------------------");
    }
}

 

 

 加了static关键字,此时输出等待三秒同时出现,因为加了synchronize的静态方法锁住的是Test这个类而不是对象。

 

posted @ 2021-03-31 01:38  袁志航  阅读(137)  评论(0编辑  收藏  举报