2016-11-03 6 views
-2

개체를 대상으로 한 자리를 예약하는 기능을 만들었습니다. 그러나 2 개의 객체가 동시에 함수에 들어가면 같은 자리를 얻습니다. 어떻게 해결할 수 있습니까?== null Java가 작동하지 않습니다.

Function 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

"동시에 입력하십시오"라는 말은이 응용 프로그램이 다중 스레드라는 의미입니까? 그렇다면 null 체크가 실패하지 않는 것이 문제입니다. 두 스레드가 같은 시간에 같은 값을 읽을 때 그 결과는 비 결정적입니다. 하나의 팬만 하나의 좌석을 확보 할 수 있도록 액세스를 동기화해야합니다. –

+0

그냥 부수적 인 말이지 만,'정적 '클래스 변수가 자신이 생각하는대로한다고 생각하지 않습니다. 이 "autoId"는이 클래스의 모든 단일 인스턴스에 대해 동일하게 적용됩니다. 시간이 지남에 따라 생성 한 개수를 본질적으로 알려줄 것입니다. – Hypino

답변

1

, 당신은 당신의 코드가 스레드 안전하다는 것을 확인해야합니다. 즉, 하나의 단일 스레드 (사람) 만 getFreeChairs 함수를 호출 할 수 있어야합니다 (한 번에 자리 예약). Java에서이를 수행하는 쉬운 방법은 동기화 된 키워드 인 메서드 정의를 사용하는 것입니다.

public synchronized int[] getFreeChairs(int aantalStoelen, Fan fan){ 
    ... 
} 
관련 문제