第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java多線程程序

Java多線程程序

溫溫醬 2022-07-06 17:29:54
我的任務是創(chuàng)建一個程序,它具有:班級Client班級Gate班級Museum通過使用類Client進入和離開。博物館一次最多可接待 5 位顧客。MuseumGate當我Clients在某個時候輸入 1000 時,輸出會給我不需要的數字。樣本輸出:Client (358) is leaving the Museum!   number of customers: 2Client (214) is entering the Museum!   number of customers: 3Client (214) is leaving the Museum!   number of customers: 2Client (73) is entering the Museum!   number of customers: 5Client (73) is leaving the Museum!   number of customers: 5Client (397) is entering the Museum!   number of customers: 5Client (76) is entering the Museum!   number of customers: 6----------------------------------------------------------------Client (930) is entering the Museum!   number of customers: 7Client (930) is leaving the Museum!   number of customers: 6Client (308) is entering the Museum!   number of customers: 6Client (183) is entering the Museum!   number of customers: 6Client (183) is leaving the Museum!   number of customers: 5----------------------------------------------------------------Client (647) is entering the Museum!   number of customers: 7Client (647) is leaving the Museum!   number of customers: 6----------------------------------------------------------------Client (540) is entering the Museum!   number of customers: 7我期望客戶會在某個隨機時間嘗試進入,當博物館中有 5 個或更多客戶時,他們將不得不等待其他線程結束它的任務。這是我的代碼:Client.javapackage 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();        }
查看完整描述

1 回答

?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

一些建議,不要使用公共靜態(tài)變量和靜態(tài)方法,如博物館.getGate() 或原子客戶計數器(這使得更難理解誰在使用什么)。此外,客戶端類應該與“計數器”邏輯完全隔離;也就是說,客戶端應該簡單地調用 gate.enter(),并且訪問檢查應該在 Gate 或 Museum 中完成。


然后是“關鍵”部分,您嘗試在其中為客戶分配“許可”,在


 while (true) {

   if (Gate.atomCustomer.get() < 5) {

     //use museum.tryEnter() instead..

     Museum.getGate(0).enter(this);

     break;

   }

 }

在這里,如果兩個線程同時調用get() ,它們都會發(fā)現客戶的數量是eg。4,他們都會進入(并發(fā)問題)。


確保只有一個客戶端獲得許可的一種方法是將嵌套調用添加到某些同步方法,例如


private synchronized boolean tryEnter() {

    if (counter<5) {

        counter++;

        return true;

    }

    else {

        return false;

    }

}

但是分配許可的更好方法是使用信號量(這樣你甚至不需要那個繁忙的循環(huán))。https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html


查看完整回答
反對 回復 2022-07-06
  • 1 回答
  • 0 關注
  • 88 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號