Java多线程程序

我的任务是创建一个程序,它具有:

  • 班级Client

  • 班级Gate

  • 班级Museum

通过使用类Client进入和离开。博物馆一次最多可接待 5 位顾客。MuseumGate

当我Clients在某个时候输入 1000 时,输出会给我不需要的数字。

样本输出:

Client (358) is leaving the Museum!   number of customers: 2

Client (214) is entering the Museum!   number of customers: 3

Client (214) is leaving the Museum!   number of customers: 2

Client (73) is entering the Museum!   number of customers: 5

Client (73) is leaving the Museum!   number of customers: 5

Client (397) is entering the Museum!   number of customers: 5

Client (76) is entering the Museum!   number of customers: 6

----------------------------------------------------------------

Client (930) is entering the Museum!   number of customers: 7

Client (930) is leaving the Museum!   number of customers: 6

Client (308) is entering the Museum!   number of customers: 6

Client (183) is entering the Museum!   number of customers: 6

Client (183) is leaving the Museum!   number of customers: 5

----------------------------------------------------------------

Client (647) is entering the Museum!   number of customers: 7

Client (647) is leaving the Museum!   number of customers: 6

----------------------------------------------------------------

Client (540) is entering the Museum!   number of customers: 7

我期望客户会在某个随机时间尝试进入,当博物馆中有 5 个或更多客户时,他们将不得不等待其他线程结束它的任务。


这是我的代码:


Client.java

package client;


import gate.Gate;

import museum.Museum;


import java.util.Random;


public class Client extends Thread {

    private static int id = 0;

    private int clientID;


    public Client() {

        Client.id++;

        this.clientID = id;

    }


    @Override

    public void run() {

        this.enterMuseum();

        this.leaveMuseum();

    }


    ///////////////////////////////////////////////////////////////////////////////////


    private void enterMuseum() {

        try {

            Thread.sleep(new Random().nextInt(401) + 100);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }



温温酱
浏览 88回答 1
1回答

月关宝盒

一些建议,不要使用公共静态变量和静态方法,如博物馆.getGate() 或原子客户计数器(这使得更难理解谁在使用什么)。此外,客户端类应该与“计数器”逻辑完全隔离;也就是说,客户端应该简单地调用 gate.enter(),并且访问检查应该在 Gate 或 Museum 中完成。然后是“关键”部分,您尝试在其中为客户分配“许可”,在&nbsp;while (true) {&nbsp; &nbsp;if (Gate.atomCustomer.get() < 5) {&nbsp; &nbsp; &nbsp;//use museum.tryEnter() instead..&nbsp; &nbsp; &nbsp;Museum.getGate(0).enter(this);&nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp;}&nbsp;}在这里,如果两个线程同时调用get() ,它们都会发现客户的数量是eg。4,他们都会进入(并发问题)。确保只有一个客户端获得许可的一种方法是将嵌套调用添加到某些同步方法,例如private synchronized boolean tryEnter() {&nbsp; &nbsp; if (counter<5) {&nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}但是分配许可的更好方法是使用信号量(这样你甚至不需要那个繁忙的循环)。https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java