商品类
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;
/*
* 线程访问变量在没锁情况下会有线程安全问题
*/
public class Demo3 extends Thread {
public Demo3(String name) {
super(name);
}
// 线程共享数据
String name;
@Override
public void run() {
int temp = Commodity.buyCommodity();
System.out.println(this.getName() + " 商品剩余数: " + temp);
}
public static void main(String[] args) {
Demo3 t1 = new Demo3("A");
Demo3 t2 = new Demo3("B");
Demo3 t3 = new Demo3("C");
Demo3 t4 = new Demo3("D");
Demo3 t5 = new Demo3("E");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
try {
// 执行完后查看剩余数
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" 商品剩余数: " + Commodity.getcNum());
}
}
// A 商品剩余数: 3
// B 商品剩余数: 0
// C 商品剩余数: 1
// E 商品剩余数: 2
// D 商品剩余数: 3
// 商品剩余数: 0