用多线程实现卖火车票

第一种:代码如下
package sell;

public class SellTicked extends Thread{

static int count=1000;//一千张票
static Object obj=new Object();
@Override
public void run() {
    while(true){
        try {
            //线程睡眠两秒
            Thread.sleep(2000);
            //线程同步锁
            synchronized(obj){
                if(count>0){
                    //输出当前线程的name
                    System.out.println(this.getName()+"当前火车票号"+count--);
                }else {
                    System.out.println("票卖完了");
                    //退出
                    System.exit(0);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
//main方法运行
public static void main(String[] args) {
    SellTicked sc=new SellTicked();
    sc.setName("第一窗口");
    sc.start();
    SellTicked sc1=new SellTicked();
    sc1.setName("第二窗口");
    sc1.start();
    SellTicked sc2=new SellTicked();
    sc2.setName("第三窗口");
    sc2.start();
}

}
第二种
package sell;

public class SellTickedRunnable implements Runnable {
static int ticked = 1000;
static Object obj = new Object();
@Override
public void run() {
while(true){
try {
Thread.sleep(2000);
synchronized(obj){
if(ticked>0){
System.out.println(Thread.currentThread().getName()+“当前窗口火车票号”+ticked–);
}else{
System.out.println(“票卖完了”);
System.exit(0);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}

    }
}
public static void main(String[] args) {
    SellTickedRunnable sr=new SellTickedRunnable();
    Thread th=new Thread(sr);
    th.setName("第一窗口");
    th.start();
    SellTickedRunnable sr2=new SellTickedRunnable();
    Thread th2=new Thread(sr2);
    th2.setName("第二窗口");
    th2.start();
    SellTickedRunnable sr3=new SellTickedRunnable();
    Thread th3=new Thread(sr3);
    th3.setName("第三窗口");
    th3.start();
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值