java Synchronize

书上一般会说,Synchronize在静态方法上使用锁的是类。

这个说法没错,但会导致一定的误解,它其实并不是说类中所有都被锁起来,其实它指的是静态方法在全局是唯一的。所以当一个线程使用这个被Synchronize修饰的方法后,其他任何线程在调用该方法都得等待,但调用其他方法是没有关系的。

class Person {
    private int age;

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return this.age;
    }
    public  synchronized static int sourcePerson() throws InterruptedException{
        Thread.sleep(10000);
        return 1;
    }
}

public class Test_tools {
    public static void main(String[] args) {
        Person p1 = new Person();
        p1.setAge(10);

        new Thread(){
            public void run() {
                try {
                    System.out.println(Person.sourcePerson());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            public void run () {
                try{
                    Thread.sleep(5000);
                    System.out.println("halou");
                    System.out.println(Person.sourcePerson());
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }
}

通过输出的时间可以进行测试。

posted @ 2021-10-24 23:38  DawnHouse  阅读(89)  评论(0)    收藏  举报