I run the main method after a while, it will always print nothing.
But if I uncomment "System.out.println(111);" and "System.out.println(222);",it will run normal i think.
I fetch the dump of 'soldWorker' thread and 'refundWorker' thread, they stop at the if
judge.
public class ProducerAndConsumer2 {
public static void main(String[] args) {
SyncTikcet2 syncTikcet = new SyncTikcet2(1);
Runnable syncSoldTicket = () -> syncTikcet.soldTicket();
Runnable syncRefundTicket = () -> syncTikcet.refund();
new Thread(syncSoldTicket, "soldWorker").start();
new Thread(syncRefundTicket, "refundWorker").start();
}
}
class SyncTikcet2 {
private Integer ticketNum;
public SyncTikcet2(Integer ticketNum) {
this.ticketNum = ticketNum;
}
public void soldTicket() {
while (true) {
if (ticketNum > 0) {
ticketNum = ticketNum - 1;
System.out.println("sold ticket,the num is" + ticketNum);
} else {
// System.out.println(111);
}
}
}
public void refund() {
while (true) {
if (ticketNum == 0) {
ticketNum = ticketNum + 1;
System.out.println("refund ticket,the num is" + ticketNum);
} else {
// System.out.println(222);
}
}
}
public Integer getTicketNum() {
return ticketNum;
}
public void setTicketNum(Integer ticketNum) {
this.ticketNum = ticketNum;
}
}