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??是程序没来得及更新数据吗? 展开
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??是程序没来得及更新数据吗? 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询