public class TicketThread implements Runnable { static int tickets = 100;// 火車票數(shù)量 Object obj = new Object(); @Override public void run() { // 出售火車票 while (true) { /* * synchronized (obj) { method(); } */ method(); // method2(); } } private synchronized void method() { if (tickets > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + tickets--); } }請(qǐng)問(wèn)這段代碼中的if (tickets > 0) 能否改成if (tickets<= 0){break;} 改完后打印的有負(fù)數(shù) ,是什么問(wèn)題呢?
2 回答
已采納

言曌博客liuyanzhao_com
TA貢獻(xiàn)164條經(jīng)驗(yàn) 獲得超117個(gè)贊
public?class?TicketThread?implements?Runnable?{ ???static?int?tickets?=?100;//?火車票數(shù)量 ???Object?obj?=?new?Object(); ??? ???@Override ???public?void?run()?{ ??????//?出售火車票 ??????while?(tickets>0)?{ ?????????method(); ??????} ?????? ???} ??? ????private??void?method()?{ ??????if?(tickets?>?0)?{ ?????????System.out.println(Thread.currentThread().getName()?+?":"?+?tickets--); ?????????try?{ ????????????Thread.sleep(100); ?????????}?catch?(InterruptedException?e)?{ ????????????e.printStackTrace(); ?????????} ??????} ???} ??? ??? ???public?static?void?main(String[]?args)?{ ??????TicketThread?ticketThread?=?new?TicketThread(); ?????? ??????Thread?t1?=?new?Thread(ticketThread,"甲站臺(tái)"); ??????Thread?t2?=?new?Thread(ticketThread,"乙站臺(tái)"); ??????Thread?t3?=?new?Thread(ticketThread,"丙站臺(tái)"); ??????Thread?t4?=?new?Thread(ticketThread,"丁站臺(tái)"); ?????? ??????t1.start(); ??????t2.start(); ??????t3.start(); ??????t4.start(); ?????? ???} }
之所以出現(xiàn)負(fù)數(shù)票,我的解釋如下。
當(dāng)票數(shù)為1的時(shí)候,有 多個(gè)線程通過(guò)了 if 判斷語(yǔ)句,然后在休眠,沒有繼續(xù)往下執(zhí)行,以至于 tickets 的數(shù)量在段時(shí)間還是 1,線程喚醒后,繼續(xù)往下執(zhí)行,接著打印票的信息。就會(huì)出現(xiàn) -1,-2 之類的票了。
解決方案:我們把 打印票的語(yǔ)句和tickets-- 的放到 sleep 前面去即可
點(diǎn)擊展開后面2條
添加回答
舉報(bào)
0/150
提交
取消