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