我只是在学习一些关于 Java 线程的知识,我想知道是否有人可以帮助我。
我创建了一个包含 10 个整数的列表。我想要做的是让多个线程进入,获取索引 0 处的整数,打印并删除它。我希望这种情况发生,直到列表中没有更多数字为止。到目前为止,这是我的代码。
public class SlothTest implements Runnable{
static ArrayList<Object> test = new ArrayList<>();
static int listSize;
public static void main(String[] args) {
for (int i = 0; i < 10; i++){
test.add(i);
}
SlothTest runner = new SlothTest();
Thread alpha = new Thread(runner);
Thread beta = new Thread(runner);
alpha.setName("Alpha thread");
beta.setName("Beta thread");
alpha.start();
beta.start();
}
@Override
public void run() {
listSize = test.size();
while (listSize > 0){
getLink();
}
}
private synchronized void getLink(){
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " printed " + test.indexOf(listSize - 1));
test.remove(0);
listSize = test.size();
}
}
有人可以帮助指出我做错的一切,可能很多。