商品类
package learn.thread;
public class Commodity {
public static int cNum = 5;
// 购买并返回剩余数
public static int buyCommodity() {
cNum -= 1;
return getcNum();
}
public static int getcNum() {
return cNum;
}
synchronized public static int buyCommodity2() {
cNum -= 1;
return getcNum();
}
synchronized public static int getcNum2() {
return cNum;
}
}
package learn.thread;
/*
* 在商品购买方法加synchronized同步关键字解决线程安全问题
* synchronized使线程排队获取带有同步关键字的方法的所属对象的对象锁,
* 持有该锁的线程能访问该对象带任何带有synchronized的方法,可称为锁重入
* 执行完带有synchronized的方法就会释放锁
*/
public class Demo4 extends Thread {
public Demo4(String name) {
super(name);
}
// 线程共享数据
String name;
@Override
public void run() {
int temp = Commodity.buyCommodity2();
System.out.println(this.getName() + " 商品剩余数: " + temp);
}
public static void main(String[] args) {
Demo4 t1 = new Demo4("A");
Demo4 t2 = new Demo4("B");
Demo4 t3 = new Demo4("C");
Demo4 t4 = new Demo4("D");
Demo4 t5 = new Demo4("E");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
try {
// 执行完后查看剩余数
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" 商品剩余数: " + Commodity.getcNum2());
}
}
// E 商品剩余数: 1
// B 商品剩余数: 0
// C 商品剩余数: 3
// A 商品剩余数: 4
// D 商品剩余数: 2
// 商品剩余数: 0