多线程安全问题(卖火车票案例)
package com.cppdy; class MyThread5 implements Runnable{ private Integer ticketCount=100;
@Override
public void run() {
while(ticketCount>0) {
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
sale();
}
} public void sale() {
System.out.println(Thread.currentThread().getName()+"卖出了第:"+(100-ticketCount+1)+"张票。");
ticketCount--;
}
} public class ThreadDemo5 { public static void main(String[] args) throws Exception{
MyThread5 mt = new MyThread5();
Thread thread1 = new Thread(mt,"窗口1");
Thread thread2 = new Thread(mt,"窗口2");
thread1.start();
thread2.start();
} }