Я пытаюсь сделать игру на основе плитки. Я сделал класс Tile
и дал каждому свой собственный Rectangle
для столкновения. Как только я создаю и обновляю их, я сохраняю их все в ArrayList
. Эта часть работает нормально, но когда я пытаюсь получить доступ к тому же ArrayList
из другого класса через getter, я не получаю ни один из элементов. Я проверить размер с моей консолью, и это дает мне правильный номер, но когда я пытаюсь на самом деле получить элемент т.е. rect.get(0)
, я получаю эти ошибки:нужна помощь с ArrayList Синхронизация
Exception in thread "Thread-3" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
Я думаю, что это вопрос безопасности резьбы, но Я пробовал все, что мог придумать, используя ключевое слово synchronize
до Collections
, но не повезло. Любая помощь могла бы быть полезна.
Отредактировано кодом. К сожалению о не размещать его ранее
public class Launcher extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 1500;
private static final int HEIGHT = 900;
private static final String title = ("Game Alpha");
volatile boolean running;
Thread CT;
Canvas canvas = new Canvas();
Dimension size = new Dimension(WIDTH, HEIGHT);
Camera camera;
Controls controls;
PlayerTest pt;
BufferStrategy BS;
Graphics graphics;
//I'm declaring the arrayList here
public ArrayList<Rectangle> bounded = new ArrayList<Rectangle>();
public Launcher() {
Sprites.resources();
controls = new Controls();
GUI();
//The camera class is the one in which I'm trying to access the list
//It's there right now just to test, I plan on changing it later
camera = new Camera(this, controls, 0, 0);
pt = new PlayerTest(this, canvas.getWidth()/2, canvas.getHeight()/2);
Tiles.tileSets();
CT = new Thread(this);
START();
}
public void GUI() {
setTitle(title);
setPreferredSize(size);
setResizable(false);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
addKeyListener(controls);
canvas.setPreferredSize(size);
canvas.setMaximumSize(size);
canvas.setMinimumSize(size);
canvas.setFocusable(false);
add(canvas);
setVisible(true);
}
public void render() {
BS = canvas.getBufferStrategy();
if(BS == null) {
canvas.createBufferStrategy(3);
return;
}
graphics = BS.getDrawGraphics();
graphics.setColor(Color.ORANGE);
graphics.fillRect(0, 0, WIDTH, HEIGHT);
Rectangle cam = new Rectangle((int)camera.getX(),
(int)camera.getY(),
camera.getWidth(),
camera.getHeight());
//Here I'm looping to get my tiles
for(int x = 0; x < 64; x++) {
for(int y = 0; y < 64; y++) {
Tiles.getTile(LevelCode.code[y][x]).setBounds(x * 50 - (int)camera.getXof(), y * 50 - (int)camera.getYof());
//Here I'm adding the rectangles from each tile into the array
bounded.add(new Rectangle(Tiles.getTile(code[y][x]).getBounds()));
}
}
pt.render(graphics);
BS.show();
graphics.dispose();
//Here after I render the tiles I clear the list, for my updates, then //repopulate
bounded.clear();
}
public ArrayList<Rectangle> getList() {
return bounded;
}
}
Мы не можем отлаживать код, который мы не видим. Пожалуйста, создайте минимальный пример для проверки. Прочитайте http://stackoverflow.com/help/mcve –
Я думаю, что это скорее проблема дизайна, чем проблема многопоточности. Вы можете создавать методы для сохранения потоков, используя ключевое слово «synchronized». Поэтому, пожалуйста, вставьте пример кода. – Petterson
Уверен, 100 очков за то, что у него 2 списка, а тот, который он пытается читать, пуст. – Kayaman