码迷,mamicode.com
首页 > 其他好文 > 详细

经典买票并发

时间:2020-11-25 12:40:31      阅读:5      评论:0      收藏:0      [点我收藏+]

标签:star   get   while   jvm   void   ant   print   oid   tst   

 

 

package com.spinlock.spinlock.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo3 {
    public static void main(String[] args) {
        TicketWindow tw = new TicketWindow();
        for (int i = 1; i < 4; i++) {
            Thread t = new Thread(tw, "TickWindow-" + i);
            t.start();
        }
    }

  static  class TicketWindow implements Runnable {
        private int tickets = 10;//车票总量

        @Override
        public void run() {
            while (true) {
//                synchronized (this) {


                ReentrantLock reentrantLock = new ReentrantLock();
                reentrantLock.lock();
                if (tickets > 0) {
                        System.out.println(Thread.currentThread().getName() + "准备出票,剩余票数:" + tickets + "张");
                        tickets--;
                        System.out.println(Thread.currentThread().getName() + "卖出一张,剩余票数:" + tickets + "张");
                        try {
                            //休眠100ms卖票完会报错ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820]
                            //Thread.sleep(100);
                            Thread.sleep(500);//出票成功后让当前售票窗口睡眠,以便让其他售票窗口卖票
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println(Thread.currentThread().getName() + "余票不足,停止售票!");
                        break;
                    }
                reentrantLock.unlock();
                }
//
        }
    }
}

加入

synchronized 或ReentrantLock  可解决并发

经典买票并发

标签:star   get   while   jvm   void   ant   print   oid   tst   

原文地址:https://www.cnblogs.com/leeego-123/p/14016899.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!