java多線程學習之線程安全問題

商品類

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
發佈了49 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章