線程安全問題的代碼實現

多線程的安全問題在於多線程程序中可以訪問共享數據.
下面是模擬多線程可共享數據的安全問題代碼:

/* 
	實現賣票案例
*/
public class RunnableImpl implements Runnable{
    // 定義一個多線程貢獻的票源
    private int ticket = 100;
    // 設置線程任務:賣票
    @Override
    public void run() {
        // 使用死循環 讓賣票操作重複執行
        while (true){
            // 先判斷票是否存在
            if (ticket > 0){
                // 使用線程睡眠提高安全問題出現的概率
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 賣票
                System.out.println("在賣"+Thread.currentThread().getName()+"線程的第:"+ticket+"張票");
                ticket--;
            }
        }
    }
}

/* 
	模擬賣票案例
	創建了3個共享線程,同時開啓,對共享的票進行出售
*/
public class Demo01Ticket {
    public static void main(String[] args) {
        // 創建實現類對象
        RunnableImpl runnable = new RunnableImpl();
        // 創建Thread類對象,構造方法中傳遞Runnable接口的實現類
        Thread thread0 = new Thread(runnable);
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        // 調用start開啓多線程
        thread0.start();
        thread1.start();
        thread2.start();
    }
}

結果發現了重複的票以及不存在的票:
在這裏插入圖片描述
在這裏插入圖片描述線程安全問題產生的原理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章