인터넷에 비슷한 질문이 많이 있다는 것을 알고 있지만 내 질문은 스레드에 관한 것이 아니라 내 코드에 관한 것입니다. 나는 선수 데이터베이스를 가지고있는 작은 앱을 만들고있다. 데이터 저장 클래스의 코드는 다음과 같습니다.자바의 두 스레드에서 동시에 변수에 액세스
public class DataManager
{
static final int NO_OF_COLUMNS = 18;
static QDatabase pdb;
public DataManager()
{
pdb = new QDatabase(NO_OF_COLUMNS);
}
public void addPlayer(Object[] playerData)
{
pdb.add(playerData);
}
public void editPlayerInfo(int type, int playerRegNo, Object data)
{
pdb.set(type, playerRegNo, data);
}
public int getPlayerRegNo(String userID)
{
return (int) pdb.getData(USER_ID, userID, REG_NO);
}
public Boolean contains(int column, Object data)
{
return pdb.contains(column, data);
}
}
나는 여러 클라이언트의 요청을 수신하고 각각에 대해 새 스레드를 만드는 서버가 있습니다. 그들은 모두 기본적으로 데이터베이스로 작동하는이 DataManager 클래스에 액세스합니다. 가능하면 모든 스레드가 어떤 방법으로 addPlayer()
및 editPlayerInfo()
메서드를 동시에 호출 할 수 있지만 동기화 문제로 인해 모든 것을 엉망으로 만들 수는 없습니까?
또한 데이터베이스를 사용할 수 있음을 알고 있습니다. 그러나 여기에서, 나는 이것이 더 쉬울 것이라고 생각했습니다. 동시에 실행되는 스레드가 약 200 개가 있다고 가정합니다. 이 문제를 해결하는 가장 좋은 방법은 무엇입니까?
나는 모든 스레드가 동시에 액세스 할 수있는 방법이 있습니까? 그렇지 않으면 서로를 기다리는 200 개의 스레드가 매우 느려질 수 있습니다.
편집 1 : 은 다음에 나오는 QDatabase 클래스가 될 때 :
public class QDatabase implements Serializable
{
private ArrayList<ArrayList<Object>> database;
public final int NOT_EXISTS = 0, REGULAR = 0, TRANSPOSE = 1;
private int lastid = -1;
//Initializer taking the number of columns as an argument
public QDatabase(int noofcolumns)
{
database = new ArrayList<ArrayList<Object>>();
addColumns(noofcolumns);
}
//Method that adds an array of objects as a new row in the database.
public void add(Object[] object)
{
for(int index = 0; index < database.size(); index++)
{
if(object != null)
{
database.get(index).add(object[index]);
lastid = database.get(0).indexOf(object[0]);
}
}
}
//Method that finds the row in a column where an instance of a particular object is found and get the values at a
//cell with the same row and a given column.
public Object getData(int columntocheck, Object check, int columntoget)
{
Object ramobject = null;
int loc = database.get(columntocheck).indexOf(check);
ramobject = database.get(columntoget).get(loc);
return ramobject;
}
//Method to check if a column contains an instance of a given object.
public Boolean contains(int column, Object objecttocheck)
{
return database.get(column).contains(objecttocheck);
}
//Method to set a given cell to an object.
public void set(int column, int row, Object object)
{
database.get(column).set(row, object);
}
}
동일한 데이터베이스에 액세스하려면 여러 스레드가 필요합니다. 그것의 서버. 그렇다면 무엇을해야합니까? – Hele
그대로 두십시오. 이 클래스는 동시 사용에는 괜찮습니다. –
동시 사용을 위해이 클래스의 사용법을 설명해 주시겠습니까? 2 개 이상의 스레드가 동시에 editPlayerInfo를 호출하면 어떻게됩니까? – Hele