public class Ticket { private int number =30; public void sale(){ if(number > 0){ System.out.println(Thread.currentThread().getName() + "卖出了" +(number--) + "票,剩余:" + number); } } public static void main(String[] args) { Ticket ticket = new Ticket(); new Thread(()->{ for (int i = 0; i < 40; i++) { ticket.sale(); } },"A").start(); new Thread(()->{ for (int i = 0; i < 40; i++) { ticket.sale(); } },"B").start(); new Thread(()->{ for (int i = 0; i < 40; i++) { ticket.sale(); } },"C").start(); } }
执行结果:
可以看出多线程情况下,数据是不正确的
传统做法
加上synchronized关键字
加上synchronized关键字看下执行结果,可以看到是有序的