【发布时间】:2017-02-07 12:28:41
【问题描述】:
我正在尝试制作基于图块的游戏。我创建了一个Tile 课程,并为每个课程提供了自己的Rectangle 用于碰撞。渲染和更新它们后,我会将它们全部存储到 ArrayList 中。这部分工作正常,但是当我尝试通过 getter 从另一个类访问相同的 ArrayList 时,我没有得到任何元素。我用控制台检查尺寸,它给了我正确的数字,但是当我尝试实际获取一个元素时
即rect.get(0),我收到这些错误:
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;
}
}
【问题讨论】:
-
我们无法调试我们看不到的代码。请构建一个可测试的最小示例。阅读stackoverflow.com/help/mcve
-
我认为这更像是一个设计问题而不是多线程问题。您可以使用关键字“同步”使方法线程保存。所以请插入一些代码示例。
-
我赌 100 SO 点他有 2 个列表,而他试图阅读的那个是空的。
-
尝试格式化您的问题。整个事情可能不应该是一个单独的段落。还要在函数调用和错误消息中使用代码块。
标签: java multithreading arraylist thread-safety