java多线程问题

【代码】packagethread;classTicketSystem{privateintticket_num=20;publicvoidbuyTicket(){if(... 【代码】
package thread;

class TicketSystem
{
private int ticket_num = 20;

public void buyTicket()
{
if(ticket_num > 0)
{
System.out.println(Thread.currentThread().getName()+" sold ticket "+ticket_num);
ticket_num --;
}
}

public void refundTicket()
{
ticket_num ++;
System.out.println(Thread.currentThread().getName()+" refund ticket "+ticket_num);
}
}

class BuyTicket implements Runnable
{
private TicketSystem buy = null;

public BuyTicket(TicketSystem buy)
{
this.buy = buy;
}
public void run()
{
for(int index = 0;index < 2;index ++)
{
buy.buyTicket();
}
}
}

class RefundTicket implements Runnable
{
private TicketSystem refund = null;

public RefundTicket(TicketSystem refund)
{
this.refund = refund;
}

public void run()
{
for(int index = 0;index < 5;index ++)
{
refund.refundTicket();
}
}
}

public class demo
{
public static void main(String [] args)
{
TicketSystem my = new TicketSystem();
new Thread(new BuyTicket(my)).start();
new Thread(new BuyTicket(my)).start();
new Thread(new RefundTicket(my)).start();

}
}

【输出】
Thread-1 sold ticket 20
Thread-0 sold ticket 20
Thread-0 sold ticket 18
Thread-1 sold ticket 19
Thread-2 refund ticket 17
Thread-2 refund ticket 18
Thread-2 refund ticket 19
Thread-2 refund ticket 20
Thread-2 refund ticket 21

【疑问】
从输出来看,线程3首次打印是17,所以线程0、1确实各执行了2次,使得ticket_num最终是16。但是线程0和1都有打印ticket_num为20??是程序没来得及更新数据吗?
展开
 我来答
陈亮424
2017-03-20 · TA获得超过634个赞
知道小有建树答主
回答量:626
采纳率:0%
帮助的人:418万
展开全部
这个应该是多线程并发问题,thread-1和thread-2一创建就进入就绪状态并且开始运行,所以当thread-1访问buyTicket()方法时,thread-2也同时可以访问buyTicket()方法,从而说明TicketSystem这个类并不是线程安全的,你可以试一下在buyTicket()方法上加上synchronized,这时候情况就不一样了
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式