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();
}
}
}