2016-11-03 134 views
-2

我已經做了一個對象的功能來保留區域中的座位。但是,如果2個對象同時進入功能,他們獲得相同的座位。我該如何解決這個問題?== null不起作用java

函數getFreeChairs返回主席位置。並設置粉絲。但是如果兩個粉絲同時進入,他們都會獲得相同的座位。

斯文

package model; 

import actors.Fan; 

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

/** 
* Created by sveno on 12-10-2016. 
*/ 
public class Vak { 
    private static int autoId = 1; 
    private String naam; 
    private int rijen, stoelenperrij, id; 
    private List<ArrayList> rows = new ArrayList<>(); 
    private Fan fan = null; 

    public Vak(String naam, int rijen, int stoelenperrij) { 
     this.naam = naam; 
     this.rijen = rijen; 
     this.stoelenperrij = stoelenperrij; 
     this.id = autoId; 
     autoId++; 

     for (int i = 0; i < rijen; i++) { 
      rows.add(new ArrayList<Fan>()); 
     } 

     for (ArrayList row : rows) { 
      for (int j = 0; j < stoelenperrij; j++) { 
       row.add(fan); 
      } 
     } 

    } 
    public void removeReserved(int rij, List<Integer> stoelen){ 
     for (int i = 0; i < stoelen.size()-1; i++) { 
      //De reserveer alle stoelen 
      ArrayList<Fan> stoel = rows.get(rij); 
      stoel.set(stoelen.get(i),fan); 
     } 
    } 

    public int getRijen() { 
     return rijen; 
    } 

    public int getStoelenperrij() { 
     return stoelenperrij; 
    } 

    public List<ArrayList> getRows() { 
     return rows; 
    } 

    public int[] getFreeChairs(int aantalStoelen, Fan fan){ 
     //Check for free seats 
     int count = 1; 
     int[] stoelenleeg = new int[aantalStoelen+1]; 
      for (int j = 0; j < rows.size(); j++) { 
       for (int k = 0; k < rows.get(j).size(); k++) { 
        if (rows.get(j).get(k) == null){ 
         stoelenleeg[count-1] = k; 
         count++; 
         //Not enough seats next to each other 
         if(count==aantalStoelen+1){ 
          stoelenleeg[aantalStoelen] = j+1; 
          for (int o = 0; o < stoelenleeg.length-1; o++) { 
           ArrayList<Fan> stoel = rows.get(j); 
           stoel.set(stoelenleeg[o],fan); 
          } 
          return stoelenleeg; 
         } 
        }else{ 
         //Not enough seats 
         stoelenleeg = new int[aantalStoelen+1]; 
         count=1; 
        } 
       } 
      } 
     return stoelenleeg; 
    } 
} 
+0

通過「同時輸入」,你的意思是這個應用程序是多線程的嗎?如果是這樣,那麼問題不在於空檢查失敗;這是當兩個線程在同一時間讀取相同的值時,結果是非確定性的。您將不得不同步訪問以確保只有一個粉絲獲得一個座位。 –

+0

只是一個方面的說明,但我不認爲'靜態'類變量做你認爲他們做的事情。這個「autoId」對於這個類的每一個實例都是一樣的,它只是基本上告訴你隨着時間的推移創建了多少個實例。 – Hypino

回答

1

如果您的代碼在併發情況下(多線程)使用,你需要確保你的代碼是線程安全的。 這意味着,只有一個單獨的線程(人)應該能夠調用getFreeChairs函數(一次預定座位) 在java中執行此操作的簡單方法是在方法定義中使用同步關鍵字:

public synchronized int[] getFreeChairs(int aantalStoelen, Fan fan){ 
    ... 
}