同步静态方法

1 . 锁 是资源类对象, 同步方法, 方法要写在资源类中
2 .资源类如果是单写的,没有实现Runnable接口.同步方法要写在资源类中,锁要求唯一,静态的同步方法,使用的锁是Card2.class
3 . 解释类.class:jvm 再去使用指定类 给每一个类创建一个 唯一的Class 对象,也就是说每个类有一个Class对象,因静态方法不能使用this关键字,则同步静态方法使用的锁是类的Class 对象
4 .

package com.qf.demo;

public class Test4 {

    public static void main(String[] args) {
        Card2 card2 = new Card2();

        Boy2 boy2 = new Boy2(card2);
        BoyBoy2 boy22 = new BoyBoy2(card2);

        Thread thread  = new Thread(boy2);
        Thread thread2  = new Thread(boy22);

        thread.start();
        thread2.start();
    }
}

/**
 * 锁 是资源类对象
 * 同步方法, 方法要写在资源类中
 * @author Administrator
 *
 *静态方法里面不能出现  this 和 super
 *
 *
 *jvm 再去使用指定类  给每一个类创建一个 唯一的Class 对象
 */
class Card2{

    private static int money = 0;   
    public synchronized static void save(){// 锁不是this  那是谁?   Card2.class
        Class  class1 = Card2.class;
        money+=1000;
        System.out.println("曹浩存了1000,还剩"+money);
    }
    public synchronized static void take(){//静态的同步方法  使用的锁  Card2.class
        money-=1000;
        System.out.println("曹浩的男朋友取了1000,还剩"+money);
    }
}

class Boy2 implements Runnable{

    Card2 card;
    public Boy2(Card2 card) {
        this.card = card;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            card.take();
        }
    }



}

class BoyBoy2 implements Runnable{
    Card2 card;
    public BoyBoy2(Card2 card) {
        this.card = card;
    }
    public void run() {
        for (int i = 0; i < 10; i++) {
                card.save();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值