买票问题,100个小朋友同时买票
资源类
public class MyTicket {
public static int num = 100;
public void sale(){
num --;
System.out.println(Thread.currentThread().getName()+"小朋友买了一张票,剩余票数"+num);
}
}
买票程序
public class MyTicketTest {
public static void main(String[] args) {
MyTicket myTicket = new MyTicket();
//线程
for (int i = 0; i < 100; i++) {
new Thread(()->{
myTicket.sale();
}).start();
}
}
}
运行结果:出现21号票被买了3次
解决方法,在Myticker类中的sale方法加上sync关键字,即
public class MyTicket {
public static int num = 100;
public synchronized void sale(){
num --;
System.out.println(Thread.currentThread().getName()+"小朋友买了一张票,剩余票数"+num);
}
}