-2
オブジェクトの領域を予約する機能を作成しました。しかし、2つのオブジェクトが同時に関数に入ると、同じ座席が得られます。これをどうすれば解決できますか?== null Javaが動作しません
関数getFreeChairsは、議長の位置を返します。ファンをセットします。しかし、2人のファンが同時にそれを入力すると、両方とも同じ座席になります。
スヴェン
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;
}
}
"同時に入力する"とは、このアプリケーションがマルチスレッドであることを意味しますか?そうであれば、問題はヌルチェックが失敗しているということではありません。 2つのスレッドが同じ時間に同じ値を読み取ると、結果は非決定的になります。 1つのファンだけが1つの座席を確保できるように、アクセスを同期させる必要があります。 –
ちょっとメモがありますが、 '静的な'クラス変数は、あなたが思っていることをするとは思いません。その "autoId"は、このクラスのすべての単一のインスタンスで同じになるでしょう、それはちょうど本質的にあなたが時間の経過とともに作成した多くを教えてくれるでしょう。 – Hypino