一段时间后我运行main方法,它将始终不打印任何内容。
但是,如果我取消注释“ System.out.println(111);”,和“ System.out.println(222);”,我认为它将正常运行。
我获取了'soldWorker'线程和'refundWorker'线程的转储,它们在if
法官处停止。
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;
}
}
答案 0 :(得分:3)
如果您尚未使字段可变,则没有理由让线程重新读取其不变的值。
尝试使用private volatile int ticketNum
我建议使用一个原始的int
,除非您必须使用对象引用。这样不仅速度更快,而且可以清楚地表明您不希望该值是null
。