多线程抢票_多线程抢票案例

说明:

利用多线程对网络抢票进行模拟演示。

技术点:

(1)实现Runnable接口

(2)重写run方法

(3)创建Thread对象调用start()方法

(4)线程锁

(5)线程休眠

package kgc.xiancheng.xi3;

//多线程抢票

public class TestThread2 implements Runnable {

private int count=10; //库存总票数

private int num=0; //抢票次数

@Override

public void run() {

int i=0;

while (true){

synchronized (this){ //线程锁

if(count==0){ //抢票完后退出

return;

}

if(Thread.currentThread().getName().equals("黄牛党")){ //对线程进行干预

if(i==1){ //只允许抢一次票

System.out.println();

System.out.println("你是黄牛!,不准你抢票了");

break;

}

i++;

}

try {

Thread.sleep(100);//模拟网络耗时

} catch (InterruptedException e) {

e.printStackTrace();

}

count--; //计数器

num++;

System.out.println();

System.out.println(Thread.currentThread().getName()+"抢到第"+num+"张票了,还有"+count+"张票");

}

}

}

public static void main(String[] args) {

TestThread2 t = new TestThread2(); //创建线程对象

Thread t1 = new Thread(t,"曹操"); //利用兄弟类启动线程体

Thread t2 = new Thread(t,"孙权");

Thread t3 = new Thread(t,"黄牛党");

t1.start(); //启动线程1

t2.start();

t3.start();

}

}

运行效果:

image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值