0
点赞
收藏
分享

微信扫一扫

synchronized部分简单用法

技术只适用于干活 2022-03-20 阅读 56
java

synchronized修饰静态/非静态方法

 public static void main(String[] args) {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                Person.m1("线程1");
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                Person.m1("线程2");
            }
        };
        t1.start();
        t2.start();
    }

public class Person {

public synchronized static void m1(String x) {
        System.out.println(x + "ing");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(x + "执行");
    }
}

在有synchronized修饰静态方法时,线程1和线程2有一个会先执行,此时就会锁住,知道执行结束才会释放锁,另一个线程才会执行。

synchronized修饰静态方法可以叫类锁,当执行一个带锁的方法,其他静态带锁的方法就不能执行了(静态的存在方法区)。

synchronized修饰非静态方法和修饰静态方法一样,只不过是在堆中,一个对象调用synchronized修饰的非静态方法时,其他非静态带锁的也不能执行了。

加锁的和不加锁的互不影响,不是同一个对象的锁互不影响,不是同一类的锁也互不影响。

读要在写之后

public static void main(String[] args) {
        Person p = new Person();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100000; i++) {
                    p.m1(1);
                }
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100000; i++) {
                    p.m1(1);
                }
            }
        };
        t1.start();
        t2.start();
        try {
            t1.join();        //不用这个主线程大概会先执行完
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(p.getMoney());
    }
public class Person {

    public static int money = 0;

    public synchronized static void m1(int x) {
        money += x;
    }

    public synchronized int getMoney() {
        return money;
    }

    public synchronized static void setMoney(int x) {
        money = x;
    }
}

x.join就是线程x执行完后面的代码才会执行。

。。。未完

举报

相关推荐

0 条评论