关于多线程的一个问题--买票Demo
自己学习的时候仿写了一个多线程买票的问题,但是输出一直不符合预期有点疑问,求解答!~
// 一个票容器类,里面有票
public class TicketContainer {
public volatile static Integer tickets = 50;
public synchronized static void buy(){
System.out.println(Thread.currentThread().getName() + "------" + tickets);
tickets--;
}
}
// 有很多很多的消费者买票
public class Customer implements Runnable{ @Override public void run() {
while (TicketContainer.tickets > 0){
TicketContainer.buy();
}
}
}
// 开始卖票
public class SaleTicket {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
executor.submit(new Customer());
}
}
}
// 输出
/**
pool-1-thread-4------50
pool-1-thread-4------49
pool-1-thread-4------48
pool-1-thread-4------47
pool-1-thread-4------46
pool-1-thread-4------45
pool-1-thread-4------44
pool-1-thread-4------43
pool-1-thread-4------42
pool-1-thread-4------41
pool-1-thread-4------40
pool-1-thread-4------39
pool-1-thread-4------38
pool-1-thread-4------37
pool-1-thread-4------36
pool-1-thread-4------35
pool-1-thread-4------34
pool-1-thread-4------33
pool-1-thread-4------32
pool-1-thread-4------31
pool-1-thread-1------30
pool-1-thread-1------29
pool-1-thread-1------28
pool-1-thread-1------27
pool-1-thread-1------26
pool-1-thread-1------25
pool-1-thread-1------24
pool-1-thread-1------23
pool-1-thread-1------22
pool-1-thread-1------21
pool-1-thread-1------20
pool-1-thread-1------19
pool-1-thread-1------18
pool-1-thread-1------17
pool-1-thread-1------16
pool-1-thread-1------15
pool-1-thread-1------14
pool-1-thread-1------13
pool-1-thread-1------12
pool-1-thread-1------11
pool-1-thread-1------10
pool-1-thread-1------9
pool-1-thread-1------8
pool-1-thread-1------7
pool-1-thread-1------6
pool-1-thread-1------5
pool-1-thread-1------4
pool-1-thread-1------3
pool-1-thread-1------2
pool-1-thread-1------1
pool-1-thread-5------0 // 很奇怪
pool-1-thread-3-------1 // 为什么
pool-1-thread-2-------2 // 求解答
pool-1-thread-4-------3 // 不是同步了吗
*/
前面的购票确实是加锁同步了,疑惑的是为什么每次最后都会有几个线程输出0,1,2,3
查看18道真题和解析