线程安全(火车票销售)

package com.hwq.arithmetic;


public class TicketOfficeTest
{


public static void main(String[] args)
{
TicketOffice officeTest = new TicketOffice();
Thread thread1 = new Thread(officeTest);
thread1.setName("售票点一");
thread1.start();
Thread thread2 = new Thread(officeTest);
thread2.setName("售票点二");
thread2.start();
Thread thread3 = new Thread(officeTest);
thread3.setName("售票点三");
thread3.start();
Thread thread4 = new Thread(officeTest);
thread4.setName("售票点四");
thread4.start();
Thread thread5 = new Thread(officeTest);
thread5.setName("售票点五");
thread5.start();
}


}
class TicketOffice implements Runnable
{
private int tickets = 0;

public void run()
{
boolean flag = true;
while(flag)
{
flag = sell();
}

}
public Boolean sell()
{
boolean flag = true;
synchronized (this)
{
if(tickets < 100)
{
tickets = tickets + 1;
System.out.println(Thread.currentThread().getName()+":"+"卖出第:"+tickets+"票");
}
else
{
flag = false;
}
}
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return flag;
}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值