商品類
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