線程安全問題的代碼

package com.itheima.demo06.ThreadSafe;
/*安全

實現賣票案例

*/
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();
            }

            //票存在,賣票 ticket--
            System.out.println(Thread.currentThread().getName()+"-->正在賣第"+ticket+"張票");
            ticket--;
        }
    }
}

}
package com.itheima.demo06.ThreadSafe;
/*ide

模擬賣票案例
建立3個線程,同時開啓,對共享的票進行出售

*/
public class Demo01Ticket {spa

public static void main(String[] args) {
    //建立Runnable接口的實現類對象
    RunnableImpl run = new RunnableImpl();
    //建立Thread類對象,構造方法中傳遞Runnable接口的實現類對象
    Thread t0 = new Thread(run);
    Thread t1 = new Thread(run);
    Thread t2 = new Thread(run);
    //調用start方法開啓多線程
    t0.start();
    t1.start();
    t2.start();
}

}線程

clipboard.png

clipboard.png

相關文章
相關標籤/搜索