天道酬勤
厚德载物

多线程synchronized实现简单的影院购票功能

多线程synchronized实现简单的影院购票功能

由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突的问题。解决该问题的机制是synchronized关键字,它包括两种用法:synchronized 方法和 synchronized 块。

synchronized 方法

通过在方法声明中加入 synchronized关键字来声明,语法如下:

public synchronized void accessVal(int newVal);

synchronized 方法控制对“对象的类成员变量”的访问:每个对象对应一把锁,每个 synchronized 方法都必须获得调用该方法的对象的锁方能执行,否则所属线程阻塞,方法一旦执行,就独占该锁,直到从该方法返回时才将锁释放,此后被阻塞的线程方能获得该锁,重新进入可执行状态。

synchronized 块

synchronized 方法的缺陷:若将一个大的方法声明为synchronized 将会大大影响效率。

Java 为我们提供了更好的解决办法,那就是 synchronized 块。 块可以让我们精确地控制到具体的“成员变量”,缩小同步的范围,提高效率。

synchronized 块:通过 synchronized关键字来声明synchronized 块,语法如下:

synchronized(syncObject)
   { 
   //允许访问控制的代码 
   }

实现简单的影院购票功能

代码如下:

package com.msl.syn;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现简单的影院购票功能 - 快乐影院
 * @author Senley
 *
 */
public class HappyCinema2 {
    public static void main(String[] args) {
        //可用位置
        List<Integer> available = new ArrayList<Integer>();
        available.add(1);
        available.add(2);
        available.add(5);
        available.add(6);
        available.add(7);
        //顾客需要的位置
        List<Integer> seats1 = new ArrayList<Integer>();
        seats1.add(1);
        seats1.add(2);
        List<Integer> seats2 = new ArrayList<Integer>();
        seats2.add(3);
        seats2.add(6);

        MslCinema m = new MslCinema(available, "Happy Cinema");
        new Thread(new HappyCustomer(m, seats1),"张三").start();
        new Thread(new HappyCustomer(m, seats2),"李四").start();
    }

}

//影院
class MslCinema{
    List<Integer> available; //可用的位置
    String name; //名称

    public MslCinema(List<Integer> available, String name) {
        this.available = available;
        this.name = name;
    }

    //购票
    public boolean bookTickets(List<Integer> seats) {
        System.out.println("欢迎光临"+this.name+",可用位置为:"+available);
        List<Integer> copy = new ArrayList<Integer>();
        copy.addAll(available);
        //相减
        copy.removeAll(seats);
        //判断大小
        if(available.size()-seats.size()!=copy.size()) {
            return false;
        }
        //成功
        available = copy;
        return true;
    }
}

//顾客
class HappyCustomer implements Runnable{
    MslCinema cinema;
    List<Integer> seats;

    public HappyCustomer(MslCinema cinema, List<Integer> seats) {
        super();
        this.cinema = cinema;
        this.seats = seats;
    }

    @Override
    public void run() {
        synchronized(cinema) {
            boolean flag = cinema.bookTickets(seats);
            if(flag) {
                System.out.println("出票成功--"+Thread.currentThread().getName()+"--位置为"+seats);
            }else {
                System.out.println("出票失败--"+Thread.currentThread().getName()+"--位置不够");     
            }
        }
    }
}

结果如下:

欢迎光临Happy Cinema,可用位置为:[1, 2, 5, 6, 7]
出票成功--张三--位置为[1, 2]
欢迎光临Happy Cinema,可用位置为:[5, 6, 7]
出票失败--李四--位置不够

“synchronized (cinema)” 意味着线程需要获得cinema对象的“锁”才有资格运行同步块中的代码。cinema对象的“锁”也称为“互斥锁”,在同一时刻只能被一个线程使用。A线程拥有锁,则可以调用“同步块”中的代码;B线程没有锁,则进入cinema对象的“锁池队列”等待,直到A线程使用完毕释放了cinema对象的锁,B线程得到锁才可以开始调用“同步块”中的代码。

赞(1) 打赏
未经允许不得转载:许我三千笔墨 » 多线程synchronized实现简单的影院购票功能
分享到: 更多 (0)

评论 28

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #1

    Having read this I believed it was extremely enlightening.
    I appreciate you finding the time and effort to put this information together.
    I once again find myself spending a lot of time both reading and leaving comments.
    But so what, it was still worthwhile!

    Twicsy2年前 (2022-06-18)回复
  2. #2

    Thanks for sharing your thoughts on Thread. Regards

    Home Decoration2年前 (2022-06-30)回复
  3. #3

    Terrific work! This is the kind of information that are
    meant to be shared around the web. Shame on Google for
    now not positioning this publish higher! Come on over and consult with
    my website . Thanks =)

    mataharibet882年前 (2022-07-06)回复
  4. #4

    With havin so much written content do you ever run into any problems of
    plagorism or copyright infringement? My blog has a lot of unique content I’ve either authored
    myself or outsourced but it looks like a lot
    of it is popping it up all over the internet without my permission. Do you
    know any solutions to help prevent content from
    being ripped off? I’d definitely appreciate it.

    VISA 040712年前 (2022-07-06)回复
  5. #5

    Greetings! I’ve been reading your site for some time now and finally got the bravery to go ahead and give you a
    shout out from Lubbock Tx! Just wanted to tell you keep up the
    fantastic job!

    boca882年前 (2022-07-06)回复
  6. #6

    Its such as you read my mind! You appear to know a lot about this, such as
    you wrote the ebook in it or something. I think that you simply can do with some percent to
    drive the message home a bit, but other than that, this is magnificent blog.
    An excellent read. I will certainly be back.

    Bách Hóa Vì Dân2年前 (2022-07-06)回复
  7. #7

    Nice blog here! Also your website loads up fast!
    Whaat web host are you using? Can Iget your affiliate
    link to your host? I wish my web site loaded up as fast ass yours
    lol
    homepage

    homepage2年前 (2022-07-06)回复
  8. #8

    I have been exploring for a bit for any high-quality articles or blog posts
    on this sort of space . Exploring in Yahoo I eventually stumbled upon this site.
    Studying this info So i am happy to express that I’ve an incredibly
    just right uncanny feeling I came upon just what I needed.
    I so much no doubt will make certain to do not fail to remember this web
    site and provides it a look regularly.

    website2年前 (2022-07-06)回复
  9. #9

    Please let me know if you’re looking for a author for your blog.
    You have some really great posts and I think I would be a good asset.
    If you ever want to take some of the load off, I’d absolutely love to write some material for your blog in exchange for a link back to mine.
    Please blast me an email if interested. Thank you!

    best driver golf2年前 (2022-07-06)回复
  10. #10

    Thanks for finally talking about > 多线程synchronized实现简单的影院购票功能-许我三千笔墨
    < Loved it!

    sagaming2年前 (2022-07-06)回复
  11. #11

    Have you ever considered about including a little bit more than just your articles?
    I mean, what you say is important and all. However
    think of if you added some great photos or videos to give your
    posts more, “pop”! Your content is excellent but with pics and videos, this website could undeniably be one of the greatest in its niche.
    Great blog!

    boca7772年前 (2022-07-06)回复
  12. #12

    Superb, what a website it is! This weblog presents useful information to us, keep it up.

    Goo7772年前 (2022-07-06)回复
  13. #13

    Thanks for a marvelous posting! I quite enjoyed reading it, you’re a great author.I will be sure to bookmark your blog and will eventually
    come back down the road. I want to encourage yourself to continue your great writing, have a nice afternoon!

    insidesocialcommerce.net2年前 (2022-07-06)回复
  14. #14

    This text is priceless. Where can I find out more?

    my web site … জন্ম নিবন্ধন

  15. #15

    I simply could not leave your website before suggesting
    that I actually enjoyed the standard information an individual supply on your visitors?
    Is gonna be back often in order to inspect new posts

  16. #16

    Hi, all is going nicely heree and ofcourse
    eery one is sharing facts, that’s trfuly excellent, keep uup writing.

    web site

    web site2年前 (2022-07-09)回复
  17. #17

    I am genuinely thankful to the owner of this site wwho has shared
    this imprdssive paragraph at here.
    web page

    web page2年前 (2022-07-11)回复
  18. #18

    Do you mind if I quote a few of your posts as long as I provide credit and sources back to your webpage?
    My blog site iis in the exact swme area of interest as yours and my users
    would really benefit from a lot of the information you provide here.
    Please let me know if this okay with you. Regards!
    Election betting parimatch webpage การพนันร้านพนัน

    webpage2年前 (2022-07-11)回复
  19. #19

    Aw, this was an exceptionally nice post. Taking the time and actual efort to create a really good article… but what can I say… I put things offf a
    whole lot and don’t manage to get nearly anything done.

    web page

    web page2年前 (2022-07-11)回复
  20. #20

    Hmm it looks like your site ate my first comment (it was extremely long) so I guess I’ll just sum
    it up what I wrote annd say, I’m thoroughly enjoying your
    blog. I too am an aspiring blog writer but I’m still new to
    everything. Do you have any tips for rookie blog writers?
    I’d definitely appreciate it.
    web site

    web site2年前 (2022-07-12)回复
  21. #21

    Howdy this is kind of of off topic but I was wondering
    if blogs use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding expertise so I wanted to get guidance
    from someone with experience. Any help would be enormously
    appreciated!

    Locanto2年前 (2022-07-14)回复
  22. #22

    Whats up this is kinda of off topic but I was wanting to know if
    blogs use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding experience so I
    wanted to get guidance from someone with experience.
    Any help would be greatly appreciated!

    http://euroopera.org2年前 (2022-07-14)回复
  23. #23

    I’m really enjoying the theme/design of your weblog. Do you ever run into
    any internet browser compatibility problems? A handful of my
    blog audience have complained about my blog not working correctly in Explorer but looks great in Safari.
    Do you have any recommendations to help fix this problem?

    judi togel2年前 (2022-07-24)回复
  24. #24

    Incredible! This blog looks just like my old one! It’s on a completely different topic but it
    has pretty much the same layout and design. Wonderful choice of colors!

  25. #25

    To think of Hawaii as just a ⁰aradise,†while there⁳ no denying its
    beauty, is to do it a disservice. hawaii drinking despite water contamination

  26. #26

    Ссылка либо кнопка под любым
    постом на канале приведет пользователя на
    вебсайт с новым зеркалом.

    Here is my web page pin up зеркало на сегодня прямо сейчас (http://www.Pegofmyart.com)

    www.Pegofmyart.com2年前 (2022-08-02)回复
  27. #27

    You’re so interesting! I don’t believe I’ve read through something like
    that before. So good to find somebody with a few unique thoughts on this subject matter.
    Really.. many thanks for starting this up. This site is something that
    is required on the internet, someone with some originality!

    boca7772年前 (2022-08-03)回复
  28. #28

    I’d like to thank yoᥙ for the efforts you’ve put in penning tһis blog.

    I гeally hope to view the ѕame hіgh-grade blog posts
    by you іn the future as ѡell. In fact, youг creative writing abilities һaѕ
    encouraged me to get my own, personal site now 😉

    Feel free to surf to my blog :: free printable january calendar

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏