美文网首页
多线程抢票案例

多线程抢票案例

作者: 信号传D | 来源:发表于2019-04-17 16:31 被阅读0次

    说明:
    利用多线程对网络抢票进行模拟演示。
    技术点:
    (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

    相关文章

      网友评论

          本文标题:多线程抢票案例

          本文链接:https://www.haomeiwen.com/subject/ikvnwqtx.html